在PHP中将数字转换为月份名称 [英] Convert number to month name in PHP

查看:111
本文介绍了在PHP中将数字转换为月份名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个PHP代码:

$monthNum = sprintf("%02s", $result["month"]);
$monthName = date("F", strtotime($monthNum));

echo $monthName;

但是它返回 12月而不是code> August 。

But it's returning December rather than August.

$ result [month] 到8,所以 sprintf 函数正在添加一个 0 使它 08

$result["month"] is equal to 8, so the sprintf function is adding a 0 to make it 08.

推荐答案

推荐的方法:

如今,您应该真正使用DateTime对象进行任何日期/时间数学。这需要你有一个PHP版本= 5.2。如Glavić的回答所示,您可以使用以下内容:

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

格式化字符用于将所有内容重置为 Unix纪元 m 格式字符是一个月的数字表示,前导零。

The ! formatting character is used to reset everything to the Unix epoch. The m format character is the numeric representation of a month, with leading zeroes.

替代解决方案:

如果您使用的是较旧的PHP版本,目前无法升级,您可以这个解决方案。
date() 函数的第二个参数接受时间戳,您可以使用 mktime() 创建一个,如下所示:

If you're using an older PHP version and can't upgrade at the moment, you could this solution. The second parameter of date() function accepts a timestamp, and you could use mktime() to create one, like so:

$monthNum  = 3;
$monthName = date('F', mktime(0, 0, 0, $monthNum, 10)); // March

如果您想要3个字母的月份名称,如 Mar ,将 F 更改为 M 。所有可用格式选项的列表可以在 PHP手册文档中找到。

If you want the 3-letter month name like Mar, change F to M. The list of all available formatting options can be found in the PHP manual documentation.

这篇关于在PHP中将数字转换为月份名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆