简体   繁体   English

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

[英]How to get the month name from a number in PHP?

I have a variable containing a month number. 我有一个包含月份数字的变量。 How can I get the name of the month from this value? 如何从该值获取月份名称?

I know I could define an array for $month_num => $month_name , but I want to know if there is a time function in PHP that can do this, without the need for an array? 我知道我可以为$month_num => $month_name定义一个数组,但是我想知道PHP中是否有一个不需要这样做的时间函数就可以做到这一点?

date("F",mktime(0,0,0,$monthnumber,1,2011));

You can get just the textual month of a Unix time stamp with the F date() format character, and you can turn almost any format of date into a Unix time stamp with strtotime() , so pick any year and a day 1 to 28 (so it's present in all 12 months) and do: 您可以使用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"));

Working example 工作实例

The nice thing about using strtotime() is that it is very flexible. 使用strtotime()是它非常灵活。 So let's say you want an array of textual month names that starts one month from whenever the script is run; 假设您想要一个从每个月运行脚本开始的一个文本月份名称的数组;

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

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

Working example 工作实例

A slightly shorter version of the accepted answer is: 可接受答案的简短版本为:

date('F', strtotime("2000-$monthnumber-01"));
  • F stands for "month name", per the table on date . Fdate表中代表“月份名称”。

  • The 2000 is just a filler for the year, and the 01 a filler for the day; 2000只是年份的填充物,而01是白天的填充物。 since we're not concerned about anything other than the month name. 因为除了月份名称外,我们什么都不关心。

Here's a demo on ideone. 这是有关ideone 的演示

You could also use: 您还可以使用:

jdmonthname(gregoriantojd($monthnumber, 1, 1), CAL_MONTH_GREGORIAN_LONG)

It's just another way. 这是另一种方式。 I don't know anything about the efficiency of this compared to @Dreaded semicolon 's answer. @Dreaded分号的答案相比,我对此的效率一无所知

Here's a demo on ideone. 这是有关ideone 的演示

For reference: 以供参考:

  • jdmonthame returns the Julian calendar month name. jdmonthame返回儒略历的月份名称。

  • gregoriantojd converts a Gregorian (currently used) calendar date to Julian (the 1, 1 part stands for day and year). gregoriantojd将公历日期(当前使用的)转换为儒略历( 1, 1代表日和年)。

use the function mktime which takes the date elements as parameters. 使用将日期元素作为参数的mktime函数。

<?php
 $month_number= 3;
 $month_name = date("F", mktime(0, 0, 0, $month_number, 10));
 echo $month_name; 
?>

Output: March 产出: 三月

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM