开发者

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

开发者 https://www.devze.com 2023-03-26 16:11 出处:网络
I have a variable containing a month number. How can I get the name 开发者_StackOverflow中文版of the month from this value?

I have a variable containing a month number. How can I get the name 开发者_StackOverflow中文版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?


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:

$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. 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.

  • The 2000 is just a filler for the year, and the 01 a filler for the day; since we're not concerned about anything other than the month name.

Here's a demo on 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.

Here's a demo on ideone.

For reference:

  • jdmonthame returns the Julian calendar month name.

  • gregoriantojd converts a Gregorian (currently used) calendar date to Julian (the 1, 1 part stands for day and year).


use the function mktime which takes the date elements as parameters.

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

Output: March

0

精彩评论

暂无评论...
验证码 换一张
取 消