Convert UTC dates to local time in PHP

前端 未结 10 1494
青春惊慌失措
青春惊慌失措 2020-11-28 07:16

I\'m storing the UTC dates into the DB using:

$utc = gmdate(\"M d Y h:i:s A\");

and then I want to convert the saved UTC date to the client

相关标签:
10条回答
  • 2020-11-28 07:44

    Given a local timezone, such as 'America/Denver', you can use DateTime class to convert UTC timestamp to the local date:

    $timestamp = *********;
    $date = new DateTime("@" . $timestamp);
    $date->setTimezone(new DateTimeZone('America/Denver'));
    echo $date->format('Y-m-d H:i:s');
    
    0 讨论(0)
  • 2020-11-28 07:45

    Date arithmetic is not needed if you just want to display the same timestamp in different timezones:

    $format = "M d, Y h:ia";
    $timestamp = gmdate($format);
    
    date_default_timezone_set("UTC");
    $utc_datetime = date($format, $timestamp);
    
    date_default_timezone_set("America/Guayaquil");
    $local_datetime = date($format, $timestamp);
    
    0 讨论(0)
  • 2020-11-28 07:51

    Here I am sharing the script, convert UTC timestamp to Indian timestamp:-

        // create a $utc object with the UTC timezone
        $IST = new DateTime('2016-12-12 12:12:12', new DateTimeZone('UTC'));
    
        // change the timezone of the object without changing it's time
        $IST->setTimezone(new DateTimeZone('Asia/Kolkata'));
    
        // format the datetime
       echo $IST->format('Y-m-d H:i:s T');
    
    0 讨论(0)
  • 2020-11-28 07:52
    $UTC_Time   = "2018-07-06 06:06:16";
    echo "UTC Time ".$UTC_Time;
    $Indian_Time = TimeConverion($UTC_Time);
    echo "<br> Indian_Time ".$Indian_Time;
    
    function TimeConverion($UTC_Time) {
      date_default_timezone_set('Europe/London');
      $sTime = date("Y-m-d h:i:sa");
      $ts3 = strtotime(date("G:i:s"))-strtotime($sTime); 
      $utc = explode(" ",$UTC_Time);
      $time = strtotime($utc[1]);
      date_default_timezone_set("Asia/Calcutta");
      $time += $ts3;  // Add the difference
      return $utc[0]." ".date("H:i:s", $time);
    }
    
    0 讨论(0)
提交回复
热议问题