4

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;
    }
}
Parth Nayak
  • 41
  • 4
  • 7
  • `convertDateTime('2017-09-12 22:45:23', false, "GMT+00:00", "GMT+04:00");` gives normal result, can you please specify what you call "wrong time span" ? – Rafik Tighilt Oct 03 '17 at 13:46
  • The main logic here is that we passed request date as date object and then it will convert it into GMT00 timespan,when i am calling that function at the time of update operation, i have timespan value as i get that timespan from database.so at the update time i called convertDatetime function like, convertDateTime(GMT00timepsan,true,GMT00,GMT+4:00) – Parth Nayak Oct 04 '17 at 05:07

1 Answers1

1

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.

matks
  • 96
  • 7