2011-03-16 74 views
1

我有一個場景,用戶選擇時間和日期(或多天),並且該值必須轉換爲當天和UTC時間。我有每個用戶的gmt抵消金額(用戶在註冊時設置)。例如:用戶的日期和時間轉換爲服務器的日期和時間在php

在東部時區的用戶選擇:

下午3:15,週一,週二,週五

我需要知道什麼時間和日期的信息將是UTC時間。解決方案必須考慮到在一個時區中的這種星期一可能是UTC時間的另一天。另外,如果時間可以轉換爲24小時格式,那將是一個加號。

爲了清楚起見,沿着陣列線的東西應返回如:

Array('<3:15 pm eastern adjusted for utc>', '<Monday adjusted for UTC>', '<Tuesday adjusted for UTC>', '<Friday adjusted for UTC>'); 

我不需要結果直接格式化爲這樣的陣列 - 這僅僅是最終目標。

我猜它涉及使用strtotime,但我只是不能完全指出如何去做。

回答

1

做了一個函數來完成這項工作:

<? 

/* 
* The function week_times() converts a a time and a set of days into an array of week times. Week times are how many seconds into the week 
* the given time is. The $offset arguement is the users offset from GMT time, which will serve as the approximation to their 
* offset from UTC time 
*/ 
// If server time is not already set for UTC, uncomment the following line 
//date_default_timezone_set('UTC'); 
function week_times($hours, $minutes, $days, $offset) 
{ 

    $timeUTC = time(); // Retrieve server time 

    $hours += $offset; // Add offset to user time to make it UTC time 

    if($hours > 24) // Time is more than than 24 hours. Increment all days by 1 
    { 

     $dayOffset = 1; 
     $hours -= 24; // Find out what the equivelant time would be for the next day 

    } 
    else if($hours < 0) // Time is less than 0 hours. Decrement all days by 1 
    { 

     $dayOffset = -1; 
     $hours += 24; // Find out what the equivelant time would be for the prior day 

    } 

    $return = Array(); // Times to return 

    foreach($days as $k => $v) // Iterate through each day and find out the week time 
    { 

     $days[$k] += $dayOffset; 

     // Ensure that day has a value from 0 - 6 (0 = Sunday, 1 = Monday, .... 6 = Saturday) 
     if($days[$k] > 6) { $days[$k] = 0; } else if($days[$k] < 0) { $days[$k] = 6; } 

     $days[$k] *= 1440; // Find out how many minutes into the week this day is 
     $days[$k] += ($hours*60) + $minutes; // Find out how many minutes into the day this time is 

    } 


    return $days; 

} 

?> 
+0

這也是我需要的東西(對於iCal的BYDAY功能,用戶在他們的時區輸入「星期一」,但我們轉換爲UTC,它可能是偏移後的「星期日/星期二」):這是個好地方我可以從:)開始 – Renee 2011-05-25 20:25:51

1
$timestamp = strtotime($input_time) + 3600*$time_adjustment; 

結果將是一個時間戳,這裏有一個例子:

$input_time = "3:15PM 14th March"; 
$time_adjustment = +3; 

$timestamp = strtotime($input_time) + 3600*$time_adjustment; 

echo date("H:i:s l jS F", $timestamp); 
// 16:15:00 Monday 14th March 

編輯:總是忘記小事,應該可以完美工作了。

+0

謝謝你的職位。唯一的一點是,用戶不會輸入特定的日期或月份,僅僅是一天(週一,週二等)。 – user396404 2011-03-16 19:08:01