0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

timestamp is justice! ~サマータイムなんて大嫌い!~

Last updated at Posted at 2017-03-10

せっかちな方への結論

サマータイムがある地域の時間計算は、
タイムスタンプ上で計算した方が安全確実!

問題点と解決案

$pdt = new DateTime('2017-03-12 02:00:00', $timeZone);
$pdtMod = clone $pdt;
$pdtMod->modify("-1 second");
$out = "{$pdtMod->format(DateTime::ISO8601)} : {$pdtMod->getTimestamp()} : {$pdtMod->format('I')}";
var_dump($out);		// -> string(41) "2017-03-12T03:59:59-0700 : 1489316399 : 1"

PDTに切り替わった直後に、
DateTime::modify() で1秒引くと、
2017-03-12T01:59:59-0800 になってくれると思いきや、
2017-03-12T03:59:59-0700 といった感じで、
2017-03-12T04:00:00-0700 から1秒引いた結果になっている!

…じゃ、どうすんのよ?ってことで↓こうする

$pdtSub = new DateTime("now", $timeZone);        // <- あとでsetTimestamp()をするから、この時点での時間はどうでもいい
$pdtSub->setTimestamp((int)($pdt->getTimestamp() - 1));
$out = "{$pdtSub->format(DateTime::ISO8601)} : {$pdtSub->getTimestamp()} : {$pdtSub->format('I')}";
var_dump($out);		// -> string(41) "2017-03-12T01:59:59-0800 : 1489312799 : 0"

( ´ー`)フゥー...

(おまけ)上記を含めたテストコード

$timeZone = new DateTimeZone('America/Los_Angeles');
$pst = new DateTime('2017-03-12 01:59:59', $timeZone);
$out = "{$pst->format(DateTime::ISO8601)} : {$pst->getTimestamp()} : {$pst->format('I')}";
var_dump($out);		// -> string(41) "2017-03-12T01:59:59-0800 : 1489312799 : 0"

$pdt = new DateTime('2017-03-12 02:00:00', $timeZone);
$out = "{$pdt->format(DateTime::ISO8601)} : {$pdt->getTimestamp()} : {$pdt->format('I')}";
var_dump($out);		// -> string(41) "2017-03-12T03:00:00-0700 : 1489312800 : 1"

// modify
$pdtMod = clone $pdt;
$pdtMod->modify("-1 second");
$out = "{$pdtMod->format(DateTime::ISO8601)} : {$pdtMod->getTimestamp()} : {$pdtMod->format('I')}";
var_dump($out);		// -> string(41) "2017-03-12T03:59:59-0700 : 1489316399 : 1"

// sub Timestamp
$pdtSub = new DateTime("now", $timeZone);
$pdtSub->setTimestamp((int)($pdt->getTimestamp() - 1));
$out = "{$pdtSub->format(DateTime::ISO8601)} : {$pdtSub->getTimestamp()} : {$pdtSub->format('I')}";
var_dump($out);		// -> string(41) "2017-03-12T01:59:59-0800 : 1489312799 : 0"

// re modify
$pstMod = clone $pst;
$pstMod->modify("-1 second");
$out = "{$pstMod->format(DateTime::ISO8601)} : {$pstMod->getTimestamp()} : {$pstMod->format('I')}";
var_dump($out);		// -> string(41) "2017-03-12T01:59:58-0800 : 1489312798 : 0"
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?