14

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?

1
  • date is good enough?
    – Nemoden
    Aug 7, 2011 at 6:27

5 Answers 5

24
date("F",mktime(0,0,0,$monthnumber,1,2011));
2
  • 7
    Although, this is the right answer, there should be an explanation of what's going on.
    – Kayla
    Apr 23, 2014 at 16:50
  • See my answer below for a slightly shorter way of doing this. Jul 6, 2014 at 14:27
16

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

1
  • An excellent idea, though the result starts from next month forward, which may not be the standard (Jan, feb, etc) output we'd expect..
    – Ben
    Aug 12, 2013 at 7:19
7

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.

2

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

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.