繁体   English   中英

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

[英]Convert local date time to UTC date time

当用户根据其时区使用'input type = date name =“日期”'&&'input type = time name =“ time”'标签输入日期和时间时,

例如:-如果来自印度(亚洲/加尔各答)时区的用户输入日期:1/22/14,时间:5:30pm,我需要将其转换为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 ) 

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

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

<?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有效。

您不能做些更简单的事情:

$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;

尝试使用以下功能将本地日期时间转换为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;
}

这是一个类似的问题。 看看使用DateTime / DateTimeZone在PHP调整时区

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM