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?
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.
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):
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With