Viewed   67 times

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.



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.

Sunday, August 28, 2022

you need to escape the a and t as both have special meaning when used as formatting options in date()

echo date('M j at h:i a');

See it in action

Monday, October 17, 2022

you need to use base_convert:

$number = $_REQUEST["number"];   # '10'
base_convert($number, 10, 36);   # 'a'
Thursday, December 15, 2022

You don't need to change the php.ini file if you use date_default_timezone_set(). Just set it to the timezone you will be working in.

Something like this should go in a config file or on the page where you're working with dates (if it is only one page):

Friday, December 23, 2022
$currentMonth = date('F');
echo Date('F', strtotime($currentMonth . " last month"));

If you don't want it relative to the current month then set:

$currentMonth = 'February';
// outputs January
Wednesday, November 2, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :