我有来自特定时区(牙买加)的时间戳,我想获取它的GMT时间戳。有没有比这个更优雅的解决方案:
$start = DateTime::createFromFormat('U', 1330560000);
$start->setTimezone(new DateTimeZone('America/Jamaica'));
$start->format('Y-m-d H:i:s');//2012-02-29 19:00:00 NO NO NO
$tz = new DateTimeZone( 'America/Jamaica' );
$transition = $tz->getTransitions($start->getTimestamp(),$start->getTimestamp());
$offset = $transition[0]['offset'];
$start = DateTime::createFromFormat('U', $params['start'] - 2*$transition[0]['offset']);
$start->setTimezone(new DateTimeZone('America/Jamaica'));
$start->format('Y-m-d H:i:s'); // "2012-03-01 05:00:00" YESSSS!!!
Unix 时间或 POSIX 时间是一个用于描述时间实例的系统,定义为自 1970 年 1 月 1 日午夜协调世界时 (UTC) 以来经过的秒数。
来源维基百科
UNIX时间戳的想法是它总是在UTC(世界上任何地方xD)。如果它不代表UTC中的时间,则不再是UNIX时间戳
这是我
类的一部分,它创建了一个格式良好的时间戳,正如我在函数的注释中所写的那样,只需传递日期、时区和标识符的字符串即可非常易于使用。
希望对您有所帮助
/**
* Default timestamp format for formatted_time
* @var string
*/
public static $timestamp_format = 'Y-m-d H:i:s';
/**
* Returns a date/time string with the specified timestamp format
* @example $time = Date::formatted_time('5 minutes ago');
* @link http://www.php.net/manual/datetime.construct
* @param string $datetime_str datetime string
* @param string $timestamp_format timestamp format
* @param string $timezone timezone identifier
* @return string
*/
public static function formatted_time($datetime_str = 'now', $timestamp_format = NULL, $timezone = NULL){
$timestamp_format = ($timestamp_format == NULL) ? Date::$timestamp_format : $timestamp_format;
$timezone = ($timezone === NULL) ? Date::$timezone : $timezone;
$tz = new DateTimeZone($timezone ? $timezone : date_default_timezone_get());
$time = new DateTime($datetime_str, $tz);
if ($time->getTimeZone()->getName() !== $tz->getName()){
$time->setTimeZone($tz);
}
return $time->format($timestamp_format);
}