2017-02-25 53 views
1

已更新Datediff在不同時區的日期時間

我需要獲取不同時區中兩個日期時間之間的小時和分鐘差異。

我有MySQL中的日期時間,以及MySQL中位置的偏移量。

我曾嘗試:

<cfset departure = CreateDateTime(2017,01,27,21,00,00)> <!--- (this time zone is +2) ---> 
<cfset arrival = CreateDateTime(2017,01,28,06,40,00)> <!--- (this time zone is -5) ---> 
<cfset depart_timezone = 2> 
<cfset arrive_timezone = -5> 

<cfset difference = datediff("h",departure,arrival)><!--- get the difference in hours ---> 

<cfset timezonedif = depart_timezone - arrive_timezone><!--- get the difference between the time zones (answer should be 7)---> 
<cfset duration = difference + timezonedif><!--- add the time zone difference to the flight difference ---> 

<cfoutput>   
(Duration: #duration# hours)<br> 
</cfoutput> 

這返回16小時,這是不正確的。差異應該是15小時40分鐘。幫助將不勝感激。在這裏呆了幾個小時。

+0

這是正確的。您提供的這些時間之間的差異是9小時。 datediff不會給你分鐘時,你使用'h',因爲它只檢查小時。如果你想允許時區,那麼你將需要計算實際時間,然後獲得差異。它不能猜測這些是不同的區域。一開始將dateAdd()時區的時間,然後傳遞它。或者DateConvert()來傳遞並傳遞它。 – haxtbh

+0

更新我的問題,並嘗試了DateAdd,但仍然沒有得到正確的結果。 –

+0

我在上次評論中提到了爲什麼會議記錄沒有返回。使用'h'只會返回上下小時數。所以16是正確的。您將需要使用幾分鐘或幾秒鐘來比較差異,並計算出總共需要多少小時和幾分鐘。標準的分鐘到小時轉換。 – haxtbh

回答

5

你正在做錯的順序。

你需要得到正確的日期/時間 - 所以添加/刪除時區差異

<cfset departure = CreateDateTime(2017,01,27,21,00,00)> <!--- (this time zone is +2) ---> 
<cfset arrival = CreateDateTime(2017,01,28,06,40,00)> <!--- (this time zone is -5) ---> 
<cfset depart_timezone = -2> 
<cfset arrive_timezone = 5> 

<cfset tzDeparture = DateAdd('h',depart_timezone,departure)> 
<cfset tzArrival = DateAdd('h',arrive_timezone,arrival)> 

然後得到的差異以分鐘爲單位總量

<cfset difference = datediff("n",tzDeparture,tzArrival)> 

然後,只需做數學題到將分鐘轉換成小時&分鐘

<cfoutput>  
    Duration Total Mins: #difference#<br> 
    Duration Hours: #int(difference/60)#<br> 
    Duration Mins: #difference MOD 60#<br> 
</cfoutput> 

輸出:

時間總計分鐘]:1000

持續時間:16個

時間敏思:40

這裏你可以看到一個例子:http://trycf.com/gist/26f5bce31db7787f4591317b7360ceb7/acf11?theme=monokai

+1

*您正在以錯誤的順序進行操作。*如果兩個值都以UTC存儲,則無論哪種方式都可以。只需取得原始值的dateDiff即可。然後添加時區偏移量(儘管只需幾分鐘,而不是幾小時)。 – Leigh

相關問題