将本地日期时间转换为UTC日期时间

时间:2014-01-22 08:24:20

标签: php datetime

当用户使用'输入类型=日期名称="日期"'输入日期和时间时&安培;&安培; '输入类型=时间名称="时间"'根据他/她的时区标记,

例如: - 如果来自印度,(亚洲/加尔各答)时区的用户输入日期:2014年1月22日和时间:下午5:30,我需要将其转换为UTC时间戳以将其存储到DB,要实现

我使用下面的代码: -

$year=substr($date,0,4);
$month=substr($date,5,2);
$day=substr($date,8);
$hour=substr($time,0,2);
$minute=substr($time,3);
$clientzone=mysql_result(mysql_query("select timezone from c_users_extra where  c_id='{$_SESSION['clientid']}'"),0,0); //Fetches the timezone of user
date_default_timezone_set($clientzone);//Setting default timezone to client timezone
$datetime = new DateTime("$year-$month-$day $hour:$minute:00");
$la_time = new DateTimeZone('UTC');
$datetime->setTimezone($la_time);
$values=$datetime->format('Y-m-d H:i:s');
$year=substr($values,0,4);
$month=substr($values,5,2);
$hour=substr($values,11,2);
$minutes=substr($values,14,2);
$seconds=substr($values,17,2);
$timestamp=mktime($hour,$minutes,$seconds,$month,$day,$year);//creating new timestamp from coverted 
print_r(getdate($timestamp));//Result :  Array ( [seconds] => 0 [minutes] => 30 [hours] => 6 [mday] => 22 [wday] => 3 [mon] => 1 [year] => 2014 [yday] => 21 [weekday] => Wednesday [month] => January [0] => 1390372200 )
//Expected Result : Array ( [seconds] => 0 [minutes] => 0 [hours] => 12 [mday] => 22 [wday] => 3 [mon] => 1 [year] => 2014 [yday] => 21 [weekday] => Wednesday [month] => January [0] => 1390372200 ) 

为什么我会得到错误的时间戳?

4 个答案:

答案 0 :(得分:3)

这是一个面向对象的例子:

<?php
  $date = '2014-01-22 18:15:00';  // assumed date is formatted correctly 
  $clientzone = 'America/New_York';  // assumed timezone is a valid one from your SQL
  $dateObj = new DateTime($date, new DateTimeZone($clientzone));
  echo "Original: " . $dateObj->format('Y-m-d H:i:sP') . "\n";

  $dateObj->setTimezone(new DateTimeZone('UTC')); // convert to UTC
  echo "Converted: " . $dateObj->format('Y-m-d H:i:sP') . "\n";
  echo "Epoch: ".$dateObj->format('U');
?>

您可以像日期函数一样格式化。 假定$ date和$ clientzone有效。

答案 1 :(得分:1)

你不能做一些更简单的事情:

$user_time = strtotime($date);
$dateTimeZone = new DateTimeZone($timezone);
// get the offset from server time (UTC)
$tzOffset = $dateTimeZone->getOffset(new DateTime());
$result_time = $user_time - $tzOffset;

答案 2 :(得分:1)

尝试以下功能将本地日期时间转换为UTC日期时间

function LocaltoUTC($date_to_convert)
{
    $local_timestamp = strtotime($date_t);

    $UTC_timestamp += ((-(5.5)) * 3600);  // 5.5 is UTC timezone or local timezone

    $gmt_datetime = gmdate('y-m-d H:i:s', $UTC_timestamp); 
    return $gmt_datetime;
}

答案 3 :(得分:0)

这是一个类似的问题。看看Adjusting time zone in PHP with DateTime / DateTimeZone

有一种解决方案和更舒适的方式来完成任务。