2014-01-22 231 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 - 硬編碼時區僅用於示例。開發者必須建立自己的邏輯來獲取時區。我並不是說我的解決方案已經可以使用了,但正如我所說的嘗試它並使其擊球 –

相關問題