简体   繁体   English

PHP:如何为偏移量DateTime设置时区

[英]PHP: How to set timezone for an offset DateTime

I'm trying to create a DateTime object offset from the present with a specific timezone. 我正在尝试创建一个具有当前时区的DateTime对象偏移量。 It works for 'today' , or an absolute value like '2017-07-16 00:00:00' , but if I try an offset, like '+1 sundays' it always has a timezone of "S". 它适用于'today'或类似于'2017-07-16 00:00:00'的绝对值,但如果我尝试使用偏移量(例如'+1 sundays' ,则时区始终为“ S”。

$dtz = date_default_timezone_get();//"America/Vancouver"
$now = new \DateTime('today', new \DateTimeZone($dtz));
$sunday = new \DateTime('+1 sundays', new \DateTimeZone($dtz));
$later = new \DateTime('2357-04-13', new \DateTimeZone($dtz));
$tz1 = $now->getTimezone()->getName();//"America/Vancouver"
$tz2 = $sunday->getTimezone()->getName();//"S"
$tz3 = $later->getTimezone()->getName();//"America/Vancouver"

How should I do this? 我应该怎么做?

The first parameter to DateTime should be a valid date/time string. DateTime的第一个参数应该是有效的日期/时间字符串。 It even takes null when using timezone as second parameter. 使用时区作为第二个参数时,它甚至为null。

'+1 sundays' is not under the category of valid date/time string. “ +1周日”不在有效的日期/时间字符串类别下。 Check the complete list here 此处查看完整列表

Below should work - 下面应该工作-

$sunday = $now->modify('+1 sundays');
echo $sunday->getTimezone()->getName();//"America/Vancouver"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM