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:51
date("F", strtotime($result["month"]))

use the above code

查看更多
我只想做你的唯一
3楼-- · 2019-01-04 18:51

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

查看更多
不美不萌又怎样
4楼-- · 2019-01-04 18:51

I know this question was asked a while ago now, but 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";
    }
}
查看更多
We Are One
5楼-- · 2019-01-04 18:53

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

查看更多
地球回转人心会变
6楼-- · 2019-01-04 18:54

You can just use monthname() function in SQL.

SELECT monthname(date_column) from table group by monthname(date_column)

查看更多
Juvenile、少年°
7楼-- · 2019-01-04 18:57

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

查看更多
登录 后发表回答