Pergunta

I have a simple function to convert a month from its number to name, i.e 10 to October

function convertToName($month) {  
    $month = date('F', mktime(0, 0, 0, $month));

    return $month;
}

This was working fine, up until, it seems, the clocks went back an hour. I'm now getting the wrong name back.

I've tried defining the timezone with date_default_timezone_set, but still nothing.

What's weird is, if you pass the function 10, it returns October, but pass it 11 or 12, it returns December, pass 1, January, 2 and 3 returns March, and so on.

I'm guessing there must be a pretty simple fix, but can't seem to find an answer anywhere,

any help would be appreciated,

thanks.

Foi útil?

Solução

Try passing a day of 1... php.net says that the 0 day of a month is actually the last day of the previous month

Outras dicas

Just supply the day and year part with whatever valid value and you will get the right result:

<?php

function convertToName($month) {  
    $month = date('F', mktime(0, 0, 0, $month, 10, 2010));

    return $month;
}

echo "1: " . convertToName(1) . "<br />";
echo "2: " . convertToName(2) . "<br />";
echo "3: " . convertToName(3) . "<br />";
echo "4: " . convertToName(4) . "<br />";
echo "5: " . convertToName(5) . "<br />";
echo "6: " . convertToName(6) . "<br />";
echo "7: " . convertToName(7) . "<br />";
echo "8: " . convertToName(8) . "<br />";
echo "9: " . convertToName(9) . "<br />";
echo "10: " . convertToName(10) . "<br />";
echo "11: " . convertToName(11) . "<br />";
echo "12: " . convertToName(12) . "<br />";

It produce the following result:

1: January
2: February
3: March
4: April
5: May
6: June
7: July
8: August
9: September
10: October
11: November
12: December

As @OptimusCrime points out, that is a rather complex way to find out the month.

I would consider

/** @desc Converts a month number (1-12) to a name
    @return mixed the month name on success; false on failure 
*/

function convertToName($month) {  

    $months = array ("January", "February", ....); // you get the drift
    return (array_key_exists($month, $months) ? $months["month"] : false);

}

obviously, this takes away the built-in internationalization that date("F") can potentially provide, but I personally like to control this myself either way - you often can't trust the server to have a specific locale installed.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top