what is wrong with the code, the first half is working correctly the second half is partly correct only the last date ie 31 is displayed incorrectly. as follows:
It’s not clear what you are trying to produce. Did you start with April because that’s the current month or because that’s the start of a fiscal year?
The main problem with the posted code is that the first parameter in the date() call is a format string. You however are suppling literal values (except for the single ‘t’ format character) so you are getting the literal value out.
How you would do this is produce the starting date that you want, in a YYYY-MM-DD format, using 01 as the DD value. You would then loop 12 times, adding one month to current date in the strtotime() call, so that at the end of the year, it rolls over into next year. You would format the date as DD-MM-YYYY when you echo it.
// use the same time throughout the following code to avoid skipping values should the script get executed right at midnight, on the last day of a month, or the last day of a year, and spans a change in a second
$now = time();
// produce the initial date. always starts at April
$date = date('Y-04-01',$now);
echo "<table><tr><th>".date("Y",strtotime('-1 year',$now))."</th>";
echo "<th>".date("Y",$now)."</th>";
echo "<th>".date("Y",strtotime('+1 year',$now))."</th></tr></table>";
// loop for 12 months
foreach(range(1,12) as $not_used)
{
// format and output the start of the month date
echo date('d-m-Y',strtotime($date,$now));
echo ' - ';
// format and output the last day of the month date
echo date("t-m-Y",strtotime($date,$now));
echo "<br>";
// add one month
$date = date('Y-m-01',strtotime("$date +1 month",$now));
}
The 2024-1-01 uses the wrong year because you have generated and echoed it before the if($months>=1 && $months<=3) { logic that’s generating the new $year value. You would need to put the $start_date generation and echoing after you have conditionally generated the new $year value.
The reason all the last day of the month values are 31 is probably because the “last day of this $months” expression, where $months is just a number, doesn’t make any sense to strtotime() and it is probably using the last day of the year, which is the 31st of December. If $months was a month name, this would probably work, except for February in leap years, since what you are suppling to strtotime() doesn’t include the year’s value, it uses the current year.