Convert number to month name in PHP

2019-01-04 18:35发布

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 date
18条回答
男人必须洒脱
2楼-- · 2019-01-04 18:59

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];
查看更多
聊天终结者
3楼-- · 2019-01-04 19:01

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

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

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

Hope this helps someone

查看更多
爷、活的狠高调
4楼-- · 2019-01-04 19:01

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));
查看更多
老娘就宠你
5楼-- · 2019-01-04 19:06
$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.

查看更多
再贱就再见
6楼-- · 2019-01-04 19:06

Use:

$name = jdmonthname(gregoriantojd($monthNumber, 1, 1), CAL_MONTH_GREGORIAN_LONG);
查看更多
太酷不给撩
7楼-- · 2019-01-04 19:07

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"));
}
查看更多
登录 后发表回答