Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert number to month name in PHP

Tags:

date

php

I have this PHP code:

$monthNum = sprintf("%02s", $result["month"]); $monthName = date("F", strtotime($monthNum));  echo $monthName; 

But it's returning December rather than August.

$result["month"] is equal to 8, so the sprintf function is adding a 0 to make it 08.

like image 447
user2710234 Avatar asked Aug 27 '13 14:08

user2710234


People also ask

How to get month name in php?

To do the conversion in respect of the current locale, you can use the strftime function: setlocale(LC_TIME, 'fr_FR. UTF-8'); $monthName = strftime('%B', mktime(0, 0, 0, $monthNumber));

How do you convert month number to month name?

Please do as follows: Select a blank cell next to the sales table, type the formula =TEXT(A2*29,"mmm") (Note: A2 is the first number of the Month list you will convert to month name), and then drag the AutoFill Handle down to other cells. Now you will see the numbers (from 1 to 12) are converted to normal month names.

How to convert month name to month number in php?

$nmonth = date('m',strtotime($month)); That will give the numerical value for $month . Thanks!


2 Answers

The recommended way to do this:

Nowadays, you should really be using DateTime objects for any date/time math. This requires you to have a PHP version >= 5.2. As shown in Glavić's answer, you can use the following:

$monthNum  = 3; $dateObj   = DateTime::createFromFormat('!m', $monthNum); $monthName = $dateObj->format('F'); // March 

The ! formatting character is used to reset everything to the Unix epoch. The m format character is the numeric representation of a month, with leading zeroes.

Alternative solution:

If you're using an older PHP version and can't upgrade at the moment, you could this solution. The second parameter of date() function accepts a timestamp, and you could use mktime() to create one, like so:

$monthNum  = 3; $monthName = date('F', mktime(0, 0, 0, $monthNum, 10)); // March 

If you want the 3-letter month name like Mar, change F to M. The list of all available formatting options can be found in the PHP manual documentation.

like image 187
Amal Murali Avatar answered Oct 17 '22 10:10

Amal Murali


Just because everyone is using strtotime() and date() functions, I will show DateTime example:

$dt = DateTime::createFromFormat('!m', $result['month']); echo $dt->format('F'); 
like image 42
Glavić Avatar answered Oct 17 '22 10:10

Glavić