我有以下PHP代码:
$monthNum = sprintf("%02s", $result["month"]);
$monthName = date("F", strtotime($monthNum));
echo $monthName;
但它返回的是December
而不是August
.
$result["month"]
等于8,因此sprintf
函数将0
加到08
.
我有以下PHP代码:
$monthNum = sprintf("%02s", $result["month"]);
$monthName = date("F", strtotime($monthNum));
echo $monthName;
但它返回的是December
而不是August
.
$result["month"]
等于8,因此sprintf
函数将0
加到08
.
The recommended way to do this:
Nowadays, you should really be using DateTime objects for any date/time math. This requires you to have a PHP version >= 5.2. As shown in Glavić's answer, you can use the following:
$monthNum = 3;
$dateObj = DateTime::createFromFormat('!m', $monthNum);
$monthName = $dateObj->format('F'); // March
!
formatting character用于将所有内容重置为Unix epoch.m
格式字符是月份的数字表示形式,带有前导零.
Alternative solution:
如果您使用的是较旧的PHP版本,目前无法升级,则可以使用此解决方案.
$monthNum = 3;
$monthName = date('F', mktime(0, 0, 0, $monthNum, 10)); // March
如果你想要三个字母的月名,比如Mar
,把F
改成M
.所有可用格式选项的列表可以在the PHP manual documentation中找到.