Here is a solution:
.
.
.
# Now loop for beginning qtr and ending qtr
while (Date_to_Days(@x) < Date_to_Days(@y)) {
my @qtr_end_date=Add_Delta_YMD(@x, 0,3,-1);
my $diff=Date_to_Days(@qtr_end_date)-Date_to_Days(@e_dt);
print "DIFF $diff\n";
if (abs($diff)<60) {
@qtr_end_date=@e_dt;
}
printf("%4d-%02d-%02d\t%4d-%02d-%02d\t%sQ%01d\n",
@x, @qtr_end_date, substr($x[0],2,2), $qtr);
@x = Add_Delta_YMD(@x, 0,3,0);
# roll over quarter to 1, beyond 4
$qtr++;
$qtr = $qtr > 4 ? 1 : $qtr;
}
.
.
.
This is tested for your two cases. I am curious why you would want output which truncates the last quarter?
HTH,
SSF