[英]Dealing with Timezones and Dates in PHP
我正在美国托管的服务器上运行一项服务,该服务读取使用本地日期创建的XML提要-当前仅在英国,但是我想确保该服务可在所有时区使用。 我的流程会查看Feed中帖子的日期,并将其与当前日期/时间进行比较(在美国的服务器上)。 我想出的解决方案将系统本地化到提要的发起者,然后创建一个时间戳,将其与“现在”进行比较:
protected function datemath($thedate){
$currenttimezone = date_default_timezone_get();
date_default_timezone_set($this->feedtimezone);
$thedate = mktime substr($thedate,11,2),substr($thedate,14,2),
substr($thedate,17,2),substr($thedate,3,2),substr($thedate,0,2),
substr($thedate,6,4));
date_default_timezone_set($currenttimezone);
return $thedate;
}
我的问题是……这是处理此问题的合理方法,还是我真正应该知道的更好,更标准化的方法?
这是我编写的用于进行时区转换的函数。 应该很不言自明:
function switch_timezone($format, $time = null,
$to = "America/Los_Angeles", $from = "America/Los_Angeles")
{
if ($time == null) $time = time();
$from_tz = new DateTimeZone($from);
$to_tz = new DateTimeZone($to);
if (is_int($time)) $time = '@' . $time;
$dt = date_create($time, $from_tz);
if ($dt)
{
$dt->setTimezone($to_tz);
return $dt->format($format);
}
return date($format, $time);
}
再检查一下其他人的代码后,我看到了该功能
strtotime($thedate);
比使用mktime简洁一些,并且允许使用不同的时间格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.