Convert number to month name in PHP

PhpDate

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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

$dt = DateTime::createFromFormat('!m', $result['month']);
echo $dt->format('F');

Solution 3 - Php

Use mktime():

<?php
 $monthNum = 5;
 $monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
 echo $monthName; // Output: May
?>

See the PHP manual : http://php.net/mktime

Solution 4 - 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));

date doesn't respect the locale, strftime does.

Solution 5 - Php

strtotime expects a standard date format, and passes back a timestamp.

You seem to be passing strtotime a single digit to output a date format from.

You should be using mktime which takes the date elements as parameters.

Your full code:
$monthNum = sprintf("%02s", $result["month"]);
$monthName = date("F", mktime(null, null, null, $monthNum));

echo $monthName;

However, the mktime function does not require a leading zero to the month number, so the first line is completely unnecessary, and $result["month"] can be passed straight into the function.

This can then all be combined into a single line, echoing the date inline.

Your refactored code:
echo date("F", mktime(null, null, null, $result["month"], 1));

...

Solution 6 - Php

If you just want an array of month names from the beginning of the year to the end e.g. to populate a drop-down select, I would just use the following;

for ($i = 0; $i < 12; ++$i) {
  $months[$m] = $m = date("F", strtotime("January +$i months"));
}

Solution 7 - Php

There are many ways to print a month from the given number. Pick one suite for you.

1. date() function along with parameter 'F'

Code example:

$month_num = 10;
echo date("F", mktime(0, 0, 0, $month_num, 10)); //output: October

2. By creating php date object using createFromFormat()

Code Example

$dateObj   = DateTime::createFromFormat('!m', $monthNum);
echo "month name: ".$dateObj->format('F'); // Output: October

3. strtotime() function

echo date("F", strtotime('00-'.$monthNum.'-01')); // Output: October

4. mktime() function

echo date("F", mktime(null, null, null, $monthNum)); // Output: October

5. By using jdmonthname()

$jd=gregoriantojd($monthNum,10,2019);
echo jdmonthname($jd,0); // Output: Oct

Solution 8 - Php

If you have the month number, you can first create a date from it with a default date of 1st and default year of the current year, then extract the month name from the date created:

echo date("F", strtotime(date("Y") ."-". $i ."-01"))

This code assumes you have your month number stored in $i

Solution 9 - Php

$monthNum = 5;
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));

I found this on https://css-tricks.com/snippets/php/change-month-number-to-month-name/ and it worked perfectly.

Solution 10 - Php

adapt as required

$m='08';
$months = array (1=>'Jan',2=>'Feb',3=>'Mar',4=>'Apr',5=>'May',6=>'Jun',7=>'Jul',8=>'Aug',9=>'Sep',10=>'Oct',11=>'Nov',12=>'Dec');
echo $months[(int)$m];

Solution 11 - Php

You need set fields with strtotime or mktime

echo date("F", strtotime('00-'.$result["month"].'-01'));

With mktime set only month. Try this one:

echo date("F", mktime(0, 0, 0, $result["month"], 1));

Solution 12 - Php

this is trivially easy, why are so many people making such bad suggestions? @Bora was the closest, but this is the most robust

/***
 * returns the month in words for a given month number
 */
date("F", strtotime(date("Y")."-".$month."-01"));

this is the way to do it

Solution 13 - Php

Am currently using the solution below to tackle the same issue:

//set locale, 
setlocale(LC_ALL,"US");

//set the date to be converted
$date = '2016-08-07';

//convert date to month name
$month_name =  ucfirst(strftime("%B", strtotime($date)));

echo $month_name;

To read more about set locale go to http://php.net/manual/en/function.setlocale.php

To learn more about strftime go to http://php.net/manual/en/function.strftime.php

Ucfirst() is used to capitalize the first letter in a string.

Solution 14 - Php

This for all needs of date-time converting

 <?php
 $newDate = new DateTime('2019-03-27 03:41:41');
 echo $newDate->format('M d, Y, h:i:s a');
 ?>

Solution 15 - Php

You can do it in just one line:

DateTime::createFromFormat('!m', $salary->month)->format('F'); //April

Solution 16 - Php

$days = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
$month = ( date('m') < 10 ) ? date('m')[1] : date('m');

That extracts the months.

Solution 17 - Php

I think using cal_info() is the easiest way to convert from number to string.

$monthNum = sprintf("%02s", $result["month"]); //Returns `08`
$monthName = cal_info(0); //Returns Gregorian (Western) calendar array
$monthName = $monthName[months][$monthNum];

echo $monthName; //Returns "August"

See the docs for cal_info()

Solution 18 - Php

This is how I did it

// sets Asia/Calcutta time zone
date_default_timezone_set("Asia/Calcutta");

//fetches current date and time
$date = date("Y-m-d H:i:s");

$dateArray = date_parse_from_format('Y/m/d', $date);
$month = DateTime::createFromFormat('!m', $dateArray['month'])->format('F');
$dateString = $dateArray['day'] . " " . $month  . " " . $dateArray['year'];

echo $dateString;

returns 30 June 2019

Solution 19 - Php

A simple tricks here you can use strtotime() function workable as per your need, a convert number to month name.

1.If you want a result in Jan, Feb and Mar Then try below one with the 'M' as a parameter inside the date.

$month=5;
$nmonth = date('M',strtotime("01-".$month."-".date("Y")));
echo $nmonth;

Output : May

/2. You can try with the 'F' instead of 'M' to get the full month name as an output January February March etc.

$month=1;
$nmonth = date('M',strtotime("01-".$month."-".date("Y")));
echo $nmonth;

Output : January

Solution 20 - Php

This respect the LC_TIME

$date = new DateTime('2022-04-05');
$mes = strftime('%B', $date->getTimestamp());

Solution 21 - Php

Use:

$name = jdmonthname(gregoriantojd($monthNumber, 1, 1), CAL_MONTH_GREGORIAN_LONG);

Solution 22 - Php

I figured everyone looking for this answer was probably just trying to avoid writing out the whole if/else statements, so I wrote it out for you so you can copy/paste. The only caveat with this function is that it goes on the actual number of the month, not a 0-indexed number, so January = 1, not 0.

function getMonthString($m){
	if($m==1){
		return "January";
	}else if($m==2){
		return "February";
	}else if($m==3){
		return "March";
	}else if($m==4){
		return "April";
	}else if($m==5){
		return "May";
	}else if($m==6){
		return "June";
	}else if($m==7){
		return "July";
	}else if($m==8){
		return "August";
	}else if($m==9){
		return "September";
	}else if($m==10){
		return "October";
	}else if($m==11){
		return "November";
	}else if($m==12){
		return "December";
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2710234View Question on Stackoverflow
Solution 1 - PhpAmal MuraliView Answer on Stackoverflow
Solution 2 - PhpGlavićView Answer on Stackoverflow
Solution 3 - PhpmintedskyView Answer on Stackoverflow
Solution 4 - PhpDerecksonView Answer on Stackoverflow
Solution 5 - PhpGregView Answer on Stackoverflow
Solution 6 - PhpTrent RenshawView Answer on Stackoverflow
Solution 7 - PhpNishad UpView Answer on Stackoverflow
Solution 8 - PhpbryaniturView Answer on Stackoverflow
Solution 9 - Phpmatthewpark319View Answer on Stackoverflow
Solution 10 - PhpzzapperView Answer on Stackoverflow
Solution 11 - PhpBoraView Answer on Stackoverflow
Solution 12 - PhpMr HeelisView Answer on Stackoverflow
Solution 13 - PhpCristo RutazihanaView Answer on Stackoverflow
Solution 14 - PhpimtaherView Answer on Stackoverflow
Solution 15 - PhpKaushik shrimaliView Answer on Stackoverflow
Solution 16 - PhpGeovany QuissangaView Answer on Stackoverflow
Solution 17 - Phpboomx09View Answer on Stackoverflow
Solution 18 - PhpVicky SalunkheView Answer on Stackoverflow
Solution 19 - PhpAvinash RautView Answer on Stackoverflow
Solution 20 - PhpBrandonjgsView Answer on Stackoverflow
Solution 21 - PhptemuriView Answer on Stackoverflow
Solution 22 - PhpFreaky TurtleView Answer on Stackoverflow