2012-05-24 16 views
4

我需要標準化和比較日期/時間字段在不同的時區。例如,你如何找到了以下兩個時間之間的時間差?...Groovy:你如何初始化和比較來自不同時區的日期/時間值?

"18-05-2012 09:29:41 +0800" 
"18-05-2012 09:29:21 +0900" 

什麼是初始化標準varaibles的日期/時間的最佳方式? 輸出需要在時區(例如+0100)中顯示差異和標準化數據,這些數據與輸入值不同且與本地環境不同。

預期輸出:

18-05-2012 02:29:41 +0100 
18-05-2012 01:29:21 +0100 
Difference: 01:00:20 

回答

3

或者,使用JodaTime包

@Grab('joda-time:joda-time:2.1') 
import org.joda.time.* 
import org.joda.time.format.* 

String a = "18-05-2012 09:29:41 +0800" 
String b = "18-05-2012 09:29:21 +0900" 

DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MM-yyyy HH:mm:ss Z"); 

def start = dtf.parseDateTime(a) 
def end = dtf.parseDateTime(b) 

assert 1 == Hours.hoursBetween(end, start).hours 
3

解決方案:

  1. 的Groovy/Java的日期對象後 1970年存儲爲毫秒數,所以不直接包含任何時區信息
  2. 使用Date.parse將新日期初始化爲指定格式的方法
  3. 使用的SimpleDateFormat類來指定所需的輸出格式
  4. 使用SimpleDateFormat.setTimeZone到specifiy輸出的時區 數據
  5. 通過使用歐洲/倫敦時區,而不是GMT將 自動調整節省每天亮燈時間
  6. 的選項日期時間模式的完整列表,請參閱here

-

import java.text.SimpleDateFormat 
import java.text.DateFormat 

//Initialise the dates by parsing to the specified format 
Date timeDate1 = new Date().parse("dd-MM-yyyy HH:mm:ss Z","18-05-2012 09:29:41 +0800") 
Date timeDate2 = new Date().parse("dd-MM-yyyy HH:mm:ss Z","18-05-2012 09:29:21 +0900") 

DateFormat yearTimeformatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss Z") 
DateFormat dayDifferenceFormatter= new SimpleDateFormat("HH:mm:ss") //All times differences will be less than a day 

// The output should contain the format in UK time (including day light savings if necessary) 
yearTimeformatter.setTimeZone(TimeZone.getTimeZone("Europe/London")) 

// Set to UTC. This is to store only the difference so we don't want the formatter making further adjustments 
dayDifferenceFormatter.setTimeZone(TimeZone.getTimeZone("UTC")) 

// Calculate difference by first converting to the number of milliseconds 
msDiff = timeDate1.getTime() - timeDate2.getTime() 
Date differenceDate = new Date(msDiff) 

println yearTimeformatter.format(timeDate1) 
println yearTimeformatter.format(timeDate2) 
println "Difference " + dayDifferenceFormatter.format(differenceDate) 
+0

Date.parse()已棄用。改爲使用SimpleDateFormat.parse()。 – rdmueller

+4

不推薦使用Java方法'Date.parse()'。然而,具有兩個參數(這裏使用)的groovy GDK'Date.parse()'不是。 – ataylor

6
import java.text.SimpleDateFormat 

def dates = ["18-05-2012 09:29:41 +0800", 
"18-05-2012 09:29:21 +0900"].collect{ 
    new SimpleDateFormat("dd-MM-yyyy HH:mm:ss Z").parse(it) 
} 
def dayDiffFormatter = new SimpleDateFormat("HH:mm:ss") 
dayDiffFormatter.setTimeZone(TimeZone.getTimeZone("UTC")) 
println dates[0] 
println dates[1] 
println "Difference "+dayDiffFormatter.format(new Date(dates[0].time-dates[1].time)) 

哇。看起來不可讀,是嗎?