Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

date - Convert number to month name in 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...