LoginSignup
6
5

More than 5 years have passed since last update.

タイムゾーンを考慮した date time string <-> unix timestamp 相互変換

Last updated at Posted at 2012-03-16

手元の適当スクリプトで一番使うやつ

<?php
/**
 * Usage:
 *
 *  $ php t.php 1324393200
 *      => 2011-12-20 15:00:00
 *  $ php t.php 1324393200 'Asia/Tokyo'
 *      => 2011-12-21 00:00:00
 *  $ php t.php '2011-12-21 00:00:00'
 *      => 1324393200
 *  $ php t.php '2011-12-21 00:00:00' 'UTC'
 *      => 1324425600
 */
if ($argc < 1) {
    exit(255);
}

if (preg_match('/^\d+$/', $argv[1])) {
    $dt = new \DateTime('@' . $argv[1]);
    if (isset($argv[2])) {
        $dt->setTimeZone(new \DateTimeZone($argv[2]));
    }

    echo $dt->format('Y-m-d H:i:s'), PHP_EOL;
} else {
    $dt = new \DateTime($argv[1], new \DateTimeZone(isset($argv[2]) ? $argv[2] : 'Asia/Tokyo'));
    $dt->setTimeZone(new \DateTimeZone('GMT'));
    echo $dt->format('U'), PHP_EOL;
}
6
5
3

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
6
5