Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime::modify and DST switch

Tags:

php

datetime

Using DateTime::modify to add an hour across a DST boundary causes it to skip an hour.

e.g.

$d = new DateTime('2015-11-01 12:00:00 AM', new DateTimeZone('America/Vancouver'));
$d->modify('+1 hour'); // 1 AM
$d->modify('+1 hour'); // 2 AM
$d->modify('+1 hour'); // 3 AM

I want to see "1 AM" twice (and then "2 AM") because time goes back an hour.

How can I get this behaviour?

like image 216
mpen Avatar asked Nov 09 '22 07:11

mpen


1 Answers

It's a bug. (credit)

To work around it, change the timezone to UTC and then back again.

$d = new DateTime('2015-11-01 12:00:00 AM', new DateTimeZone('America/Vancouver'));

$tz = getTimezone();
$d->setTimezone(new DateTimeZone('UTC'));
$d->modify('+1 hour'); 
$d->modify('+1 hour'); 
$d->modify('+1 hour'); 
$d->setTimezone($tz);
echo $d->format('d-M-Y g:ia'); // 01-Nov-2015 2:00am
like image 55
mpen Avatar answered Nov 15 '22 12:11

mpen