phpmktime

PHP Mktime shows 2 March's when I dump foreach month


I've been using the following function fine until the other day when the clocks went forward:

function months($month_format="F") {
$array = array();
for ($i = 1; $i <=12; $i++) {
    $array[$i]['string'] = date($month_format, mktime(0,0,0,$i));
    $array[$i]['int'] = date('m', mktime(0,0,0,$i));
}
return $array;
}

It outputs an array with:

Since the other day (like 2 days ago, when the clocks went forward in the UK), the function seems to be showing me 2 march months and 0 Februarys....

Very very strange... I'm using rethinkdb with their eachPosTime function... not sure if this is causing it.

I tried using a different function, but still using mktime:

function months(){
 $start_month = 1;
 $end_month = 12;
 $start_year = date("Y");
 $array = array();
 for($m=$start_month; $m<=12; ++$m){

    echo $m.'<br>';

    $array[$m]['string'] = date('F', mktime(0,0,0,$m));
    $array[$m]['int'] = date('m', mktime(0,0,0,$m));

       if($start_month == 12 && $m==12 && $end_month < 12) 
       {
           $m = 0;
           $start_year = $start_year+1;
       }
 //echo date('F Y', mktime(0, 0, 0, $m, 1, $start_year)).'<br>';
 if($m == $end_month) break;
}
return $array;
}

Still, I am having no luck. Check the image here, which shows the output of the months() function:

Output of the months() function


Solution

  • This is not to do with the clocks changing, but the time of the month, and the entirely unhelpful signature of the mktime function.

    When you leave out parameters from a "mktime" call, they are filled in with today's date. In your case, you specified month without day or year, so when you ask for mktime(0, 0, 0, 2); it will fill in today's day and year, and look for the 29th February 2021 - a day that doesn't exist. Since the time library "overflows" dates, this becomes the 1st March.

    The solution is to pass an explicit day to "mktime", as in mktime(0,0,0,$m,1) or to use a less confusing function.