Home > Article > Backend Development > Why Does My PHP Code Convert Month Numbers to December Instead of the Correct Month?
Converting Numbers to Month Names in PHP
Problem:
When using PHP code to convert a numeric month value (e.g., 8 for August) to its corresponding month name, the code is incorrectly returning "December" instead of "August."
Code:
<code class="php">$monthNum = sprintf("%02s", $result["month"]); $monthName = date("F", strtotime($monthNum)); echo $monthName;</code>
Root Cause:
The sprintf() function is adding a leading zero to month values less than 10 (e.g., 8 becomes 08), which is then causing date() to interpret the value as December (month 12).
Recommended Solution (PHP >= 5.2):
Use DateTime objects for date/time manipulation:
<code class="php">$monthNum = 3; $dateObj = DateTime::createFromFormat('!m', $monthNum); $monthName = $dateObj->format('F'); // March</code>
Alternative Solution (Older PHP Versions):
<code class="php">$monthNum = 3; $monthName = date('F', mktime(0, 0, 0, $monthNum, 10)); // March</code>
The above is the detailed content of Why Does My PHP Code Convert Month Numbers to December Instead of the Correct Month?. For more information, please follow other related articles on the PHP Chinese website!