php convert datetime to UTC

后端 未结 16 875
無奈伤痛
無奈伤痛 2020-11-27 12:30

I am in need of an easy way to convert a date time stamp to UTC (from whatever timezone the server is in) HOPEFULLY without using any libraries.

相关标签:
16条回答
  • 2020-11-27 12:56

    try

    echo date('F d Y', strtotime('2010-01-19 00:00:00'));

    will output:

    January 19 2010

    you should change format time to see other output

    0 讨论(0)
  • 2020-11-27 12:58

    Do this way:

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

    or simply

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

    to get "NOW" in UTC.

    Check the reference:

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

    0 讨论(0)
  • 2020-11-27 12:58

    Convert local time zone string to UTC string.
    e.g. New Zealand Time Zone

    $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
      if $datetime = "2016-02-01 00:00:01", $output = "2016-01-31 11:00:01";
      if $datetime = "2016-02-29 23:59:59", $output = "2016-02-29 10:59:59";
    • NZST: UTC+12:00
      if $datetime = "2016-05-01 00:00:01", $output = "2016-04-30 12:00:01";
      if $datetime = "2016-05-31 23:59:59", $output = "2016-05-31 11:59:59";

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

    0 讨论(0)
  • 2020-11-27 12:58

    As strtotime requires specific input format, DateTime::createFromFormat could be used (php 5.3+ is required)

    // 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);
    
    0 讨论(0)
提交回复
热议问题