PHP date()函数在时钟更改后返回错误的值

问题描述:

I have a simple function to convert a month from its number to name, i.e 10 to October

function convertToName($month) {  
    $month = date('F', mktime(0, 0, 0, $month));

    return $month;
}

This was working fine, up until, it seems, the clocks went back an hour. I'm now getting the wrong name back.

I've tried defining the timezone with date_default_timezone_set, but still nothing.

What's weird is, if you pass the function 10, it returns October, but pass it 11 or 12, it returns December, pass 1, January, 2 and 3 returns March, and so on.

I'm guessing there must be a pretty simple fix, but can't seem to find an answer anywhere,

any help would be appreciated,

thanks.

我有一个简单的函数可以将一个月从其编号转换为名称,即10到10月 p> \ n

  function convertToName($ month){
 $ month = date('F',mktime(0,0,0,$ month)); 
 
返回$ month; 
  } 
  code>  pre> 
 
 

这个工作正常,直到看起来时钟已经过了一个小时。 我现在回错了名字。 p>

我尝试用date_default_timezone_set定义时区,但仍然没有。 p>

有什么奇怪的, 如果你传递函数10,它返回10月,但是传递11或12,它返回12月,传递1,1月,2和3返回3月,依此类推。 p>

我' 猜测必须有一个非常简单的修复,但似乎无法在任何地方找到答案, p>

任何帮助将不胜感激, p>

谢谢 。 p> div>

Try passing a day of 1... php.net says that the 0 day of a month is actually the last day of the previous month

Just supply the day and year part with whatever valid value and you will get the right result:

<?php

function convertToName($month) {  
    $month = date('F', mktime(0, 0, 0, $month, 10, 2010));

    return $month;
}

echo "1: " . convertToName(1) . "<br />";
echo "2: " . convertToName(2) . "<br />";
echo "3: " . convertToName(3) . "<br />";
echo "4: " . convertToName(4) . "<br />";
echo "5: " . convertToName(5) . "<br />";
echo "6: " . convertToName(6) . "<br />";
echo "7: " . convertToName(7) . "<br />";
echo "8: " . convertToName(8) . "<br />";
echo "9: " . convertToName(9) . "<br />";
echo "10: " . convertToName(10) . "<br />";
echo "11: " . convertToName(11) . "<br />";
echo "12: " . convertToName(12) . "<br />";

It produce the following result:

1: January
2: February
3: March
4: April
5: May
6: June
7: July
8: August
9: September
10: October
11: November
12: December

As @OptimusCrime points out, that is a rather complex way to find out the month.

I would consider

/** @desc Converts a month number (1-12) to a name
    @return mixed the month name on success; false on failure 
*/

function convertToName($month) {  

    $months = array ("January", "February", ....); // you get the drift
    return (array_key_exists($month, $months) ? $months["month"] : false);

}

obviously, this takes away the built-in internationalization that date("F") can potentially provide, but I personally like to control this myself either way - you often can't trust the server to have a specific locale installed.