如何从PHP中的数字中获取月份名称?

hd.*_*hd. 13 php datetime date

我有一个包含月份编号的变量.如何从此值中获取月份名称?

我知道我可以定义一个数组$month_num => $month_name,但我想知道PHP中是否有一个时间函数可以做到这一点,而不需要数组?

Dre*_*lon 23

date("F",mktime(0,0,0,$monthnumber,1,2011));
Run Code Online (Sandbox Code Playgroud)

  • 虽然这是正确的答案,但应该对正在发生的事情作出解释. (5认同)

Pet*_*tai 14

您可以使用F date()格式字符获得Unix时间戳的文本月份,并且您可以使用strtotime()将几乎任何格式的日期转换为Unix时间戳,因此选择任何一年和第1天至第28天(因此它存在在所有12个月)并做:

$written_month = date("F", strtotime("2001-$number_month-1"));

// Example - Note: The year and day are immaterial:
// 'April' == date("F", strtotime("2001-4-1"));
Run Code Online (Sandbox Code Playgroud)

工作实例

使用的好处strtotime()是它非常灵活.因此,假设您想要一个文本月份名称数组,从脚本运行之日起一个月开始;

<?php
for ($number = 1; $number < 13; ++$number) {

    // strtotime() understands the format "+x months"
    $array[] = date("F", strtotime("+$number months"));
}
?>
Run Code Online (Sandbox Code Playgroud)

工作实例


Dan*_*ett 5

接受答案的略短版本是:

date('F', strtotime("2000-$monthnumber-01"));
Run Code Online (Sandbox Code Playgroud)
  • F代表"月份名称",根据表格date.

  • 2000只是当年01的填充物,也是当天的填充物; 因为我们不关心月份名称以外的任何事情.

这是关于ideone 的演示.