190

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.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
user2710234
  • 3,177
  • 13
  • 36
  • 54
  • 6
    Unless you convert this to a full date (08-21-2013), or something that would closely resemble a date `strtotime` has no idea what your trying to do. Alternatively just use a switch for something like this. – phpisuber01 Aug 27 '13 at 14:05
  • sorry - the $result["month"] is 8 because i have an SQL Query that says select MONTH(date time) from table... so in the table its a full date format – user2710234 Aug 27 '13 at 14:18
  • 1
    But `strtotime` has no idea what "8" means. `strtotime` parses complete timestamps like "2012-05-12 08:43:12". What does "8" mean in this context? – deceze Aug 27 '13 at 14:43
  • why not just: `echo date( "F", time() );` ? For example, `echo date( "F", strtotime("2019-03-09") );` will output "March" – Rob Watts Mar 28 '19 at 15:07

22 Answers22

424

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.

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • 42
    This doesn't respect the LC_TIME locale and will always output the month name in English. – Dereckson Aug 28 '14 at 01:15
  • 2
    I never saw this on SO - Fatal error: Call to a member function format() on a non-object in Noone from 48 pluses didnt have this? – Jaroslav Štreit Jan 08 '15 at 12:12
  • @JaroslavŠtreit: Could you post the code which you're having issues with? In https://eval.in/ or some similar pastebin site? – Amal Murali Jan 09 '15 at 05:28
  • 2
    Why do you say that we "should really" be using DateTime objects for this? DateTime objects are useful, but the date() function is much simpler as has much lower overhead (in terms of both speed and memory) if all you're trying to do is something simple like this. – orrd Jan 06 '16 at 09:51
  • 4
    @orrd: If the speed difference between date() and DateTime turns out to be the bottleneck of the application you're building, I'd say you have bigger problems to worry about. For actual applications, where you are inevitably going to need to do other things with the dates, then having it be in an object is a superior as it's got a easier to read API. – Amal Murali Jan 06 '16 at 14:46
  • 1
    @orrd: Kinda surprised merely suggesting DateTime warrants a downvote :P So much for DRY: http://www.artima.com/intv/dry.html – Amal Murali Jan 06 '16 at 14:51
  • Thanks for the "!" part - PHP does some really unexpected things without that bit :) – gazareth Jan 31 '17 at 11:25
  • $monthNum = date('m')+1; $dateObj = DateTime::createFromFormat('!m', $monthNum); $monthName = $dateObj->format('F'); It works fine, add or minus to monthNum brings the desired result. Whereas $monthNum = date('m')-2; $monthName = date("F", strtotime($monthNum)); echo $monthName; It gives wrong results, – Elango Paul Victor Feb 08 '20 at 17:20
44

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

$dt = DateTime::createFromFormat('!m', $result['month']);
echo $dt->format('F');
Glavić
  • 42,781
  • 13
  • 77
  • 107
36

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

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
mintedsky
  • 1,073
  • 13
  • 18
  • Is there any way to get month number when month name is passed ? – Nisha May 29 '18 at 07:40
  • @Nisha use paramter `"m"` it will return the month as a 2 digit number as a `string`. e.g. January = 01, February = 02 – Zac Nov 10 '18 at 06:51
27

IntlDateFormatter::format

To do the conversion in respect of a specific locale, you can use the IntlDateFormatter class:

function getMonthName ($locale, $monthNumber) {
    $formatter = new IntlDateFormatter($locale);
    $formatter->setPattern('MMMM');

    return $formatter->format(mktime(0, 0, 0, $monthNumber));
}

$monthName = getMonthName('fr_FR', 8); // août

This requires the intl extension. The class is available in PHP 5.3.0+.

Historical - before PHP 8.1.0

Before the IntlDateFormatter class, the strftime function was used. This function has been deprecated in PHP 8.1.0.

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.

Dereckson
  • 1,340
  • 17
  • 30
  • Thanks, working nice! However, I had to use `$monthName = utf8_encode(strftime('%B', mktime(0, 0, 0, $monthNumber)));` in order to display accentuated characters like in 'Août' – Roubi Nov 26 '18 at 01:42
  • 3
    @Roubi As utf8_encode is documented as "Encodes an ISO-8859-1 string to UTF-8", it means your û was an ISO-8859-1. If you want UTF-8 everywhere (and your PHP code doesn't run by default in UTF-8), you can use LC_ALL instead of LC_TIME in setlocale. – Dereckson Nov 30 '18 at 21:35
  • strftime is now deprecated – shelbypereira May 20 '23 at 17:47
  • @shelbypereira Indeed, the IntlDateFormatter class can be now used instead. Updating the answer to mention it. – Dereckson May 21 '23 at 01:20
21

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

...

Community
  • 1
  • 1
Greg
  • 21,235
  • 17
  • 84
  • 107
  • Strangely `date("F", mktime(null, null, null, 2));` returns `March` instead of `February`. – Mischa Mar 30 '15 at 14:35
  • 5
    Well noticed, @Mischa. If you don't set a day (the 5th parameter), `mktime` will use the current day. Today is 31st. What is the 31st February? :) – Greg Mar 31 '15 at 12:11
  • There is an error in your refactored code. `1` isn't being provided as 5th parameter to `mktime` but as 3rd parameter to `date` which would not produce expected results – Ejaz Jul 01 '15 at 17:54
13

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
Nishad Up
  • 3,457
  • 1
  • 28
  • 32
11

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
bryanitur
  • 111
  • 1
  • 4
10

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"));
}
Trent Renshaw
  • 512
  • 7
  • 14
  • I like this approach, but wasn't familiar with the syntax, so I would add this as an alternative `for ($counter = 1; $counter <= 12; $counter ++) { $months[$counter] = date('F', strtotime("December +$counter months")); }` – domaci_a_nas Mar 02 '22 at 11:42
8

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];
zzapper
  • 4,743
  • 5
  • 48
  • 45
7
$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.

matthewpark319
  • 1,214
  • 1
  • 14
  • 16
3

You can do it in just one line:

DateTime::createFromFormat('!m', $salary->month)->format('F'); //April
Dharman
  • 30,962
  • 25
  • 85
  • 135
Kaushik shrimali
  • 1,178
  • 8
  • 15
2

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));
Bora
  • 10,529
  • 5
  • 43
  • 73
2

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

Mr Heelis
  • 2,370
  • 4
  • 24
  • 34
2

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.

igr
  • 10,199
  • 13
  • 65
  • 111
  • for a compatibility with utf8 try : utf8_encode(ucfirst(strftime("%B", strtotime($date)))); – Mimouni Aug 09 '18 at 11:21
  • 1
    @Mimouni This isn't needed as the utf8_encode function converts ISO-8859-1 strings into UTF-8, but through LC_ALL, the code can be instructed to output UTF-8, for example if you use en_US.UTF-8 instead of US. – Dereckson Nov 30 '18 at 21:44
2

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');
 ?>
imtaher
  • 430
  • 4
  • 9
2
$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.

M--
  • 25,431
  • 8
  • 61
  • 93
1

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

Avinash Raut
  • 1,872
  • 20
  • 26
0

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

boomx09
  • 13
  • 4
0

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

Vicky Salunkhe
  • 9,869
  • 6
  • 42
  • 59
0

This respect the LC_TIME

$date = new DateTime('2022-04-05');
$mes = strftime('%B', $date->getTimestamp());
Brandonjgs
  • 194
  • 2
  • 10
-1

Use:

$name = jdmonthname(gregoriantojd($monthNumber, 1, 1), CAL_MONTH_GREGORIAN_LONG);
temuri
  • 2,767
  • 5
  • 41
  • 63
-1

My approach

$month = date('m');
$months_of_year = array(
    array('month' => '01', 'translation' => 'janeiro'),
    array('month' => '02', 'translation' => 'fevereiro'),
    array('month' => '03', 'translation' => 'março'),
    array('month' => '04', 'translation' => 'abril'),
    array('month' => '05', 'translation' => 'maio'),
    array('month' => '06', 'translation' => 'junho'),
    array('month' => '07', 'translation' => 'julho'),
    array('month' => '08', 'translation' => 'agosto'),
    array('month' => '09', 'translation' => 'setembro'),
    array('month' => '10', 'translation' => 'outubro'),
    array('month' => '11', 'translation' => 'novembro'),
    array('month' => '12', 'translation' => 'dezembro'),
);
$current_month = '';
foreach ($months_of_year as $key => $value) 
{
    if ($value['month'] == $month){
        $current_month = $value['translation'];  
        break;  
    }
}
echo("mes:" . $current_month);