[PHP] timezone 적용 date()

PHP 2020. 6. 2. 15:38

 

 

// date()와 동일하고 마지막에 timezone 파라미터를 하나 더 받아 처리할 수 있음
function _date($format, $timestamp=false, $timezone=false)
{
    $timestamp = $timestamp ? $timestamp : time();
    $timezone  = $timezone ? $timezone : date_default_timezone_get();
 
    try {
        $dt = new DateTime('now', new DateTimeZone($timezone));
    } catch (Exception $e) {
        // timezone 세팅에 문제가 있을 경우 그냥 date() 반환
        return date($format, $timestamp);
    }
 
    $dt->setTimestamp($timestamp);
 
    return $dt->format($format);
}
 
 
$tzList = [
    date_default_timezone_get(),
    'Asia/Seoul',
    'Asia/Singapore',
    'Asia/Ho_Chi_Minh',
    'Asia/Bangkok',
    'America/Los_Angeles',
    'America/New_York',
    'Europe/London',
    'Europe/Paris',
    'Asia/Srednekolymsk',
    'invalid timezone' // 비정상 timezone
];
$ts = time();
foreach ($tzList as $tz) {
    printf("%-17s\t%s\n", $tz, _date('Y-m-d H:i:s', $ts, $tz));
}
 
 
// 결과값은 아래와 같음
Asia/Seoul          2020-06-02 15:29:57 
Asia/Seoul          2020-06-02 15:29:57
Asia/Singapore      2020-06-02 14:29:57
Asia/Ho_Chi_Minh    2020-06-02 13:29:57
Asia/Bangkok        2020-06-02 13:29:57
America/Los_Angeles 2020-06-01 23:29:57
America/New_York    2020-06-02 02:29:57
Europe/London       2020-06-02 07:29:57
Europe/Paris        2020-06-02 08:29:57
Asia/Srednekolymsk  2020-06-02 17:29:57
invalid timezone    2020-06-02 15:29:57

 

 

 

 

 

 

Posted by bloodguy
,