我有这个函数用于将请求日期转换为 GMT00 unix 时间跨度并将该时间跨度存储到数据库中。
当我尝试将 GMT00 时间跨度转换为有效的 GMT 时区(如 GMT+4:00)时,下面的函数会返回错误的时间跨度
/** * 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;
}
}
最佳答案
这里的问题是那一行:return gmdate($format, $date->getTimestamp());
时间戳不带时区。unix 时间戳是自 1970 年 1 月 1 日午夜以来花费的秒数,UTC。 无论时区如何,都是一样的。因此,当您使用 $date->getTimestamp()
时,您会“丢失”$date< 的时区元数据
对象。
所以你可以通过修改来修复你的代码
return gmdate($format, $date->getTimestamp());
通过
return $date->format($format);
希望对您有所帮助。
关于PHP时区转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46361242/