Search code examples
phpstrtotimemktime

php - mktime or strtotime?


I'm trying to convert 2010-02 to February, 2010. But, I keep getting December, 1969

I've tried using mktime, strtotime, and some combination of the two, but still haven't been able to do it...

This is what I tried most recently...

$path_title = date('F, Y', mktime(0,0,0,2,0,2010));

Solution

  • This would be a way to do it:

    $dateString = '2010-02';
    list($year, $month) = explode('-', $dateString);
    $timeStamp = mktime(0, 0, 0, $month, 1, $year);
    echo date('F, Y', $timestamp);
    

    Another way would be:

    $dateString = '2010-02';
    $timestamp = strtotime($dateString . '-01');
    echo date('F, Y', $timestamp);
    

    strtotime can't handle ambiguous dates like "2010-02", but if you make it a full date it should work.

    Otherwise, you may want to look into something like DateTime::createFromFormat.