Format::datetime and timezones when converting from timestamp

Format::datetime and timezones when converting from timestamp

hisservanthisservant Posts: 5Questions: 3Answers: 0

Not sure if this is a bug or just an edge case implementation that requires custom modification, but I hope this code will be helpful to others in the future.

I'm using Format::datetime in the PHP library in order to convert timestamps. For example:

...
Field::inst( 'create_time' )
                ->set(Field::SET_CREATE) //only write on create, not edit
                ->validator( 'Validate::dateFormat', array(
                    "empty" => false,
                    "format"  => 'n-j-Y H:i',
                    "message" => "Please use the date selector to choose a time"
                ) )
                ->getFormatter( 'Format::datetime', array(
                    'from' => 'U',
                    'to' =>   'n-j-Y H:i'
                ) )
                ->setFormatter( 'Format::datetime', array(
                    'from' => 'n-j-Y H:i',
                    'to' =>   'U'
                ) )
...

Per the PHP docs ( http://php.net/manual/en/datetime.createfromformat.php ), "The timezone parameter and the current timezone are ignored when the time parameter either contains a UNIX timestamp (e.g. 946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00)."

Thus, this means that the generated date is always UTC - regardless of the current timezone. This results in incorrect display. I solved this by writing the following custom formatter:

$datetimeFormatterZ = function($val, $data, $opts)
{
    $date = \DateTime::createFromFormat($opts['from'], $val);

    // Allow empty strings or invalid dates
    if ($date)
    {
        $date->setTimeZone(new \DateTimeZone(date_default_timezone_get()));
        return $date->format($opts['to']);
    }
    return null;
}

Answers

  • allanallan Posts: 61,840Questions: 1Answers: 10,134 Site admin

    Thanks for posting this. I think this is expected, but I will dig into it and make sure that is the case. I can see how it could be annoying and perhaps it should be an option of the formatter.

    Thanks for posting your workaround!

    Regards,
    Allan

This discussion has been closed.