Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get two March when looping out month names?

Tags:

php

Why do I get two March instead of February then March when running the following code?

<?php

  for($i=1; $i<= 12; $i++){

  //MONTH NAME
  $monthName = strftime('%B', mktime(0, 0, 0, $i));

  if($i <= 9){
    $monthNr = "0".$i;
  }
  else{
    $monthNr = $i;
  }

  echo $monthNr . ':' . ucfirst($monthName) ."\n";

  }
?>

Output:

01:January
02:March
03:March
04:April
05:May
06:June
07:July
08:August
09:September
10:October
11:November
12:December
like image 734
Björn C Avatar asked Mar 04 '23 15:03

Björn C


1 Answers

It's because of this:

(from the mktime function reference)

Arguments may be left out in order from right to left; any arguments thus omitted will be set to the current value according to the local date and time.

If the current day is greater than the last day of the specified month, the extra days will extend the resulting timestamp into the next month. In this case today is the 30th, so February 30th becomes March 2nd.

If you add a day to mktime you'll get the result you're expecting.

$monthName = strftime('%B', mktime(0, 0, 0, $i, 1));
like image 158
Don't Panic Avatar answered Mar 15 '23 20:03

Don't Panic