PHP timezone conversion issue

Viewed 594

I have this function which is used to covert request date into GMT00 unix time span and store that time span into database.

When i am trying to convert GMT00 time span to valid GMT timezone like GMT+4:00 then below function return wrong time span

/**
     * Convert date time from one timezone to another timezone
     *
     * @param $datetime (string): Date Time value which needs to be converted
     * @param $is_timestamp (boolean): If $datetime is a timestamp then true, otherwise false
     * @param $stimezone (string): Timezone from which to convert date and time
     * @param $dtimezone (string): Timezone in which to convert date and time
     * @param $format (string): Format in which you need date and time
     *
     * @return (misc) Converted date time string, null on failure
     */
public static function convertDateTime($datetime, $is_timestamp = false, $stimezone = "GMT+00:00", $dtimezone = "GMT+00:00", $format = null) {
    if ($is_timestamp) {
        $datetime = date("Y-m-d H:i:s", $datetime);

    } else {
        $datetime = date("Y-m-d H:i:s", strtotime($datetime));
    }

    try {
        $date = new \DateTime($datetime, new \DateTimeZone($stimezone));
        $date->setTimezone(new \DateTimeZone($dtimezone));

        if (!empty($format)) {
            //return $date->format($format);
            return gmdate($format, $date->getTimestamp());

        } else {
            return $date->getTimestamp();
        }

    } catch (\Exception $e) {
        return null;
    }
}
1 Answers

The problem here is that line: return gmdate($format, $date->getTimestamp());

The timestamp does not carry the timezone. The unix timestamp is the number of seconds spent since the 1st of January 1970 at midnight, UTC. It is the same, no matter the timezone. So when you use $date->getTimestamp() you 'lose' the timezone metada of the $date object.

So you can fix your code by modifying

return gmdate($format, $date->getTimestamp());

by

return $date->format($format);

I hope this helps.

Related