简体   繁体   中英

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. 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".

$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. It even takes null when using timezone as second parameter.

'+1 sundays' is not under the category of valid date/time string. Check the complete list here

Below should work -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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