4

我需要标准化和比较不同时区的日期/时间字段。例如,您如何找到以下两次之间的时差?...

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

用日期/时间初始化标准变量的最佳方法是什么?输出需要在与传入值不同且与本地环境不同的时区(例如 +0100)中显示差异和规范化数据。

预期输出:

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

3 回答 3

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

哇。看起来不可读,是吗?

于 2012-05-24T10:25:59.137 回答
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
于 2012-05-24T09:22:19.050 回答
3

解决方案:

  1. Groovy/Java Date 对象存储为 1970 年之后的毫秒数,因此不直接包含任何时区信息
  2. 使用Date.parse方法将新日期初始化为指定格式
  3. 使用SimpleDateFormat类指定所需的输出格式
  4. 使用SimpleDateFormat.setTimeZone指定输出数据的时区
  5. 通过使用欧洲/伦敦时区而不是 GMT,它将自动调整夏令时
  6. 有关日期时间模式选项的完整列表,请参见此处

-

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)
于 2012-05-24T09:07:31.613 回答