2
3

More than 5 years have passed since last update.

phpでタイムゾーンの"日の出/日没"時間、"時間差"を取得

Posted at

DateTimeDateTimeZone 関数が便利だし、ソースコードが少しエレガントになった気がしてくるから、これから積極的に使っていきたい!

TimeZone関連の2つの関数を作ってみた。1つは2つのタイムゾーンの時間差を返す関数。もう1つは特定のタイムゾーンの”日の出”と”日没"の時間を現地でデフォルトタイムゾーンの時間で返す関数です。

phpがサポートしているタイムゾーンの一覧はここで確認できる。
http://www.php.net/manual/ja/timezones.php

2つのタイムゾーンの時間差を取得

/**
 * 
 * @param string $timezoneName1
 * @param string $timezoneName2
 * @return array
 */
function getTimezoneTimeDifference($timezoneName1, $timezoneName2 = null) {
    $timezone1 = new DateTimeZone($timezoneName1);
    $timezone2 = new DateTimeZone($timezoneName2);

    $date1 = new DateTime("now", $timezone1);
    $date2 = new DateTime("now", $timezone2);

    $offset = $timezone1->getOffset($date1) - $timezone2->getOffset($date2);
    $hour   = floor($offset / 3600);
    $minute = ($offset - ($hour * 3600)) / 60;

    return array(
        'time'   => $hour.':'.$minute,
        'offset' => $offset);
}

echo "TimeDifference: " . $diff['time'];
$diff = getTimezoneTimeDifference('Asia/Tokyo', 'Europe/Stockholm');
echo $diff['time'] . "<br />";

// Output  
// TimeDifference: 8:0;

 

タイムソーンの”日の出”と”日没"の時間を現地でデフォルトタイムゾーンの時間で取得

/**
 * 
 * @param string $timezoneName
 * @param string $localTime
 * @param string $format
 * @return array
 */
function getSunTime($timezoneName, $localTime = false, $format = "H:i")
{
    $timezone = new DateTimeZone($timezoneName);
    $location = $timezone->getLocation();

    $sunrise = date_sunrise(time(), SUNFUNCS_RET_TIMESTAMP, 
                            $location['latitude'], $location['longitude']);
    $sunset  = date_sunset(time(), SUNFUNCS_RET_TIMESTAMP, 
                           $location['latitude'], $location['longitude']);

    if ($localTime == true) {
        $diff = getTimezoneTimeDifference(date_default_timezone_get(), $timezoneName);
        $sunrise += $diff['offset'];
        $sunset  += $diff['offset'];
    }

    $date1 = new DateTime("now", $timezone);
    $sunrise = $date1->setTimestamp($sunrise)->format($format);
    $sunset  = $date1->setTimestamp($sunset)->format($format);

    return array(
        'sunrise' => $sunrise,
        'sunset'  => $sunset
    );
}

date_default_timezone_set('Asia/Tokyo');

echo "Stockholm Time: ";
echo print_r(getSunTime("Europe/Stockholm", false), true);

echo "Tokyo Time: ";
echo print_r(getSunTime("Europe/Stockholm", true), true);

// Output  
// Stockholm Time: Array ( [sunrise] => 07:37 [sunset] => 16:26 )   
// Tokyo Time: Array ( [sunrise] => 15:37 [sunset] => 00:26 )   
2
3
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
2
3