source

php datetime을 UTC로 변환

itover 2022. 12. 21. 22:30
반응형

php datetime을 UTC로 변환

라이브러리를 사용하지 않고 날짜 타임스탬프를 UTC(서버가 있는 시간대)로 쉽게 변환할 수 있는 방법이 필요합니다.

strtotime을 사용하여 지정된 문자열에서 타임스탬프를 생성하고(현지 시간으로 해석), gmdate를 사용하여 포맷된 UTC 날짜로 가져옵니다.

요청하신 대로 간단한 예를 다음에 제시하겠습니다.

echo gmdate('d.m.Y H:i', strtotime('2012-06-28 23:55'));

날짜 시간 사용:

$given = new DateTime("2014-12-12 14:18:00");
echo $given->format("Y-m-d H:i:s e") . "\n"; // 2014-12-12 14:18:00 Asia/Bangkok

$given->setTimezone(new DateTimeZone("UTC"));
echo $given->format("Y-m-d H:i:s e") . "\n"; // 2014-12-12 07:18:00 UTC

getTimezone과 setTimezone을 시험해 보겠습니다.예를 들어보겠습니다.

(단, 이것은 클래스를 사용합니다)

갱신:

어떤 수업도 받지 않고 다음과 같은 것을 시도해 볼 수 있습니다.

$the_date = strtotime("2010-01-19 00:00:00");
echo(date_default_timezone_get() . "<br />");
echo(date("Y-d-mTG:i:sz",$the_date) . "<br />");
echo(date_default_timezone_set("UTC") . "<br />");
echo(date("Y-d-mTG:i:sz", $the_date) . "<br />");

메모: 타임존을 원래대로 되돌려야 할 수도 있습니다.

다음과 같이 합니다.

gmdate('Y-m-d H:i:s', $timestamp)

또는 간단히 말하면

gmdate('Y-m-d H:i:s')

UTC에서 "NOW"를 얻습니다.

참조를 확인합니다.

http://www.php.net/manual/en/function.gmdate.php

날짜 형식이 YYY-MM-HH dd:mm:ss인 경우 실제로 "datetime 문자열" 끝에 UTC를 추가하고 strtotime을 사용하여 변환함으로써 php를 속일 수 있습니다.

date_default_timezone_set('Europe/Stockholm');
print date('Y-m-d H:i:s',strtotime("2009-01-01 12:00"." UTC"))."\n";
print date('Y-m-d H:i:s',strtotime("2009-06-01 12:00"." UTC"))."\n";

다음과 같이 인쇄됩니다.

2009-01-01 13:00:00
2009-06-01 14:00:00

보시다시피 서머타임 문제도 해결됩니다.

조금 이상한 방법으로 해결할 수 있습니다.:)

로컬 시간대 문자열을 UTC 문자열로 변환합니다.
예: 뉴질랜드 표준 시간대

$datetime = "2016-02-01 00:00:01";
$given = new DateTime($datetime, new DateTimeZone("Pacific/Auckland"));
$given->setTimezone(new DateTimeZone("UTC"));
$output = $given->format("Y-m-d H:i:s"); 
echo ($output);
  • NZDT: UTC+13:00
    $datetime = "2016-02-01 00:00:01"인 경우, $output = "2016-01-31 11:00:01";
    $datetime = "2016-02-29 23:59:59"인 경우, $output = "2016-02-29 10:59:59";
  • NZST: UTC+12:00
    $datetime = "2016-05-01 00:00:01"인 경우, $output = "2016-04-30 12:00:01";
    $datetime = "2016-05-31 23:59:59"인 경우, $output = "2016-05-31 11:59:59";

https://en.wikipedia.org/wiki/Time_in_New_Zealand

PHP 5.2.0 이후 이용 가능한 PHP의 DateTime 클래스를 사용해도 괜찮으시다면 상황에 맞는 몇 가지 시나리오가 있습니다.

  1. 를 가지고 있는 경우$givenDtUTC로 변환할 DateTime 개체는 UTC로 변환됩니다.

    $givenDt->setTimezone(new DateTimeZone('UTC'));
    
  2. 원본이 필요한 경우$givenDt나중에 클론된 개체를 변환하기 전에 지정된 DateTime 개체를 복제할 수도 있습니다.

    $utcDt = clone $givenDt;
    $utcDt->setTimezone(new DateTimeZone('UTC'));
    
  3. datetime 문자열만 있는 경우.$givenStr = '2018-12-17 10:47:12'먼저 datetime 객체를 작성한 후 변환합니다.주의: 이 전제는$givenStr는, PHP 의 설정된 타임 존에 있습니다.

    $utcDt = (new DateTime($givenStr))->setTimezone(new DateTimeZone('UTC'));
    
  4. 지정된 datetime 문자열이 PHP 구성과 다른 시간대에 있는 경우 올바른 시간대를 지정하여 datetime 개체를 만듭니다(PHP가 지원하는 시간대 목록 참조).이 예에서는 암스테르담의 현지 시간대를 상정하고 있습니다.

    $givenDt = new DateTime($givenStr, new DateTimeZone('Europe/Amsterdam'));
    $givenDt->setTimezone(new DateTimeZone('UTC'));
    

strtotime에는 특정 입력 형식이 필요하므로 DateTime::createFromFormat을 사용할 수 있습니다(php 5.3+ 필요).

// set timezone to user timezone
date_default_timezone_set($str_user_timezone);

// create date object using any given format
$date = DateTime::createFromFormat($str_user_dateformat, $str_user_datetime);

// convert given datetime to safe format for strtotime
$str_user_datetime = $date->format('Y-m-d H:i:s');

// convert to UTC
$str_UTC_datetime = gmdate($str_server_dateformat, strtotime($str_user_datetime));

// return timezone to server default
date_default_timezone_set($str_server_timezone);

이 방법을 사용하는 경우가 있습니다.

// It is not importnat what timezone your system is set to.
// Get the UTC offset in seconds:
$offset = date("Z");

// Then subtract if from your original timestamp:
$utc_time = date("Y-m-d H:i:s", strtotime($original_time." -".$offset." Seconds"));

작동하다 모두 대부분의 경우.

http://php.net/manual/en/function.strtotime.php 또는 문자열이 아닌 시간 컴포넌트를 사용해야 하는 경우 http://us.php.net/manual/en/function.mktime.php 를 참조하십시오.

PHP 5 이상에서는 datetime:: format 함수를 사용할 수 있습니다(http://us.php.net/manual/en/datetime.format.php) 설명서 참조).

 echo strftime( '%e %B %Y' , 
    date_create_from_format('Y-d-m G:i:s', '2012-04-05 11:55:21')->format('U')
    );  // 4 May 2012

해라

에코 날짜('F d Y', strtotime('2010-01-19 00:00:00');

출력:

2010년 1월 19일

다른 출력을 보려면 포맷 시간을 변경해야 합니다.

임의의 타임존에서 다른 타임 스탬프의 형식을 지정하는 범용 정규화 기능.다른 시간대 사용자의 데이터 타임스탬프를 관계형 데이터베이스에 저장하는 데 매우 유용합니다.하고 UTC와 함께 합니다.gmdate('Y-m-d H:i:s')

/**
 * Convert Datetime from any given olsonzone to other.
 * @return datetime in user specified format
 */

function datetimeconv($datetime, $from, $to)
{
    try {
        if ($from['localeFormat'] != 'Y-m-d H:i:s') {
            $datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
        }
        $datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
        $datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
        return $datetime->format($to['localeFormat']);
    } catch (\Exception $e) {
        return null;
    }
}

사용방법:

$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta'];

$to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC'];

datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"

Phil Pafford의 답변에 대한 개선 사항(Y-d-mTG:i:sz'를 이해하지 못하고 시간대를 되돌릴 것을 제안함)그래서 이것을 제안합니다(일반/텍스트의 HMTL 형식을 변경하여 복잡해졌습니다).

<?php
header('content-type: text/plain;');
$my_timestamp = strtotime("2010-01-19 00:00:00");

// stores timezone
$my_timezone = date_default_timezone_get();
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date)\n";

// changes timezone
date_default_timezone_set("UTC");
echo date("Y-m-d\TH:i:s\Z", $my_timestamp)."\t\t (ISO8601 UTC date)\n";
echo date("Y-m-d H:i:s", $my_timestamp)."\t\t (your UTC date)\n";

// reverts change
date_default_timezone_set($my_timezone);
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date is back)\n"; 
?>

또는 다음과 같이 시도해 볼 수 있습니다.

<?php echo (new DateTime("now", new DateTimeZone('Asia/Singapore')))->format("Y-m-d H:i:s e"); ?>

다음과 같이 출력됩니다.

2017-10-25 17:13:20 아시아/싱가포르

읽기 전용 날짜만 표시하려면 텍스트 입력 상자의 값 속성 내에서 이 값을 사용할 수 있습니다.

지역/국가를 표시하지 않으려면 'e'를 삭제하십시오.

사용자의 로컬시스템에 설정된 임의의 타임존의 UTC 시간을 취득하려면 다음 절차를 수행합니다(이것은 웹 어플리케이션이 다른 타임존을 UTC에 저장하는 데 필요합니다).

  1. Javascript(클라이언트 측):

    var dateVar = new Date();
    var offset = dateVar.getTimezoneOffset();
    //getTimezoneOffset - returns the timezone difference between UTC and Local Time
    document.cookie = "offset="+offset;
    
  2. Php(서버측):

    public function convert_utc_time($date)
    {
        $time_difference = isset($_COOKIE['offset'])?$_COOKIE['offset']:'';
        if($time_difference != ''){
            $time = strtotime($date);
            $time = $time + ($time_difference*60); //minutes * 60 seconds
            $date = date("Y-m-d H:i:s", $time);
        } //on failure of js, default timezone is set as UTC below
        return $date;
    }
    ..
    ..
    //in my function
    $timezone = 'UTC';
    $date = $this->convert_utc_time($post_date); //$post_date('Y-m-d H:i:s')
    echo strtotime($date. ' '. $timezone)
    

언급URL : https://stackoverflow.com/questions/2095703/php-convert-datetime-to-utc

반응형