KKL Michael
KKL Michael

Reputation: 795

Convert month number to month name

I want to convert month number to the month name. I have tried the below code:

A.

$month = 01;
$monthName = date("M", mktime(0, 0, 0, $month);

B.

$month = 01;
$monthName = date("M", mktime(0, 0, 0, $month, 10));

C.

$month = 01;
$monthName = date("M", mktime(0, 0, 0, $month, 1, 2015));    

Here is my questions:

(1) Are they perform same output? Which one should I choose?

(2) I don't understand the 10 after the $month variable. What does it means?

(3) Any other ways to convert month number to the month name except the A, B, C?

Upvotes: 1

Views: 5316

Answers (2)

André Chalella
André Chalella

Reputation: 14112

Do they perform the same output?

Most days, yes. However, if the current day is 31 and $month is a 30-day month, A will return the next month. February is problematic too, naturally.

Which one should I choose?

  • A is wrong
  • B is ok (I'd use 1 instead of 10 though)
  • C is too much

Choose B.

What does the 10 after the $month variable mean?

It's the day of the month of the date you're creating with mktime(). If you leave it out, PHP assumes you want the same as the current day of the month. That's why A is wrong (bug described above).

Any other ways?

function getShortMonthNameByNumber($monthNum)
    switch ($monthNum) {
        case 1:
            return "Jan";
        case 2:
            return "Feb";
        case 3:
            return "Mar";
        // etc
    }

However, I'd stick with B.

Your code uses date("M"), which returns the short name of the month (Jan, Feb etc). If you want full names (January, February etc), use "F" instead of "M".


NOTE: NEVER write numbers with leading zeroes in source code, because this usually means octal (instead of decimal). In your examples, $month = 08 or $month = 09 would explode your script.

Upvotes: 1

Niranjan N Raju
Niranjan N Raju

Reputation: 11987

Without using mktme , use date()

echo date("F");// directly to get current month ie October

If you alerady have date and in that you want to extract month bane, use strrtotime() with date()

$date = "2015-09-11";
echo date("F",strtotime($date));// will echo September

Upvotes: 0

Related Questions