Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

date

php

datetime

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?

like image 535
hd. Avatar asked Aug 07 '11 06:08

hd.


People also ask

How do you convert a number to a month name?

Select the cells containing the month names that you want to convert. Press CTRL+1 from your keyboard or right-click and select “Format Cells” from the context menu that appears. This will open the Format Cells dialog box. Click on the Number tab and select “Custom” from the list under Category.

How to Display months in PHP?

To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp parameter for the date() function. Like this: echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y'))); This will also work (it's typically used to get the last day of the previous month):


2 Answers

date("F",mktime(0,0,0,$monthnumber,1,2011));
like image 163
Dreaded semicolon Avatar answered Oct 10 '22 00:10

Dreaded semicolon


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

like image 26
Peter Ajtai Avatar answered Oct 10 '22 02:10

Peter Ajtai