Wrong date return after strftime use in PHP

614 views Asked by At

I have this little function allowing me to format a date:

function formatDateTime($date, $lang) {
    setlocale(LC_TIME, $lang);
    return strftime('%A %e %B %Y', $date);
}

I'm using it like this:

formatDateTime('2016-12-27', 'fr_FR');

The problem I have is the function return me a wrong date in french jeudi 1 janvier 1970.

It should be Mardi 27 décembre 2016.

Do you help me to find why ?

Thanks.

1

There are 1 answers

0
feeela On

strftime expects a UNIX timestamp, not a date string.

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

http://php.net/manual/en/function.strftime.php

You can either put in a UNIX timestamp as returned by time() or convert the input to a timestamp:

<?php

function formatDateTime($date, $lang) {
    setlocale(LC_TIME, $lang);

    if(is_numeric($date)) {
        /* UNIX timestamps must be preceded by an "@" for the DateTime constructor */
        $datetime = new DateTime('@' . $date);
    }
    else {
        /* …anything else is fine (mostly) fine to digest for DateTime */
        $datetime = new DateTime($date);
    }

    /* Now use strftime() or… */
//  return strftime('%A %e %B %Y', $datetime->getTimestamp());

    /* …instead of using strftime() it now may be better to use
     * the format() method from the DateTime object:*/
    return $datetime->format('%A %e %B %Y');
}

See also: http://php.net/datetime