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

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

问题描述

我有这个 PHP 代码:

I have this PHP code:

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

echo $monthName;

但它返回的是 December 而不是 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

如果您想要像 Mar 这样的 3 个字母的月份名称,请将 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天全站免登陆