2014-01-22 230 views
-1

当用户根据他/她的时区使用'input type = date name ='date''& &'input type = time name =“time”'标记输入日期和时间时,将当地日期时间转换为UTC日期时间

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

我用下面的代码: -

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

为什么我得到这个wron g时间戳?

+2

对不起,但这是一个巨大的矫枉过正,为什么使用所有'substr's?当你可以直接得到这些值 –

+0

[offtopic]当我通过'substr'在PHP中看到从日期开始获得年/月/日时,我感觉自己很年轻... [/ offtopic]在你的问题中添加想要的结果 –

+0

To从日期和时间输入标签中检索确切的值.. –

回答

2

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

<?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被认为是有效的。

+0

谢谢你,伙计,这对我有用.. –

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; 
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; 
} 
+0

丑解决方案使用unix时间戳和硬编码时区偏移量,并且不考虑夏令时,而不是使用DateTime和DateTimeZone对象 –

+0

@Mark Ba​​ker - 硬编码时区仅用于示例。开发者必须建立自己的逻辑来获取时区。我并不是说我的解决方案已经可以使用了,但正如我所说的尝试它并使其击球 –

相关问题