【问题标题】:Converting UTC Date to GMT in Groovy / Java在 Groovy / Java 中将 UTC 日期转换为 GMT
【发布时间】:2012-09-18 04:38:55
【问题描述】:

我正在使用 SoupUI,我需要调整一个日期/时间 (UTC),以响应 GMT 日期/时间。我回复的日期如下:

2012-11-09T00:00:00+01:00

我想把它转换成

2012-11-08T23:00:00Z

不幸的是,我缺乏 Java 技能,因此也缺乏 Groovy 技能,无法独自完成这项工作。我对日期转换做了很多搜索,但直到现在我仍然无法找到我想要的东西。我会继续寻找。如果我确实设法获得了解决方案,那么我会在这里发布。

【问题讨论】:

标签: groovy utc datetime-format gmt date-conversion


【解决方案1】:

假设时区部分没有冒号,我相信这应该可行:

// Your input String (with no colons in the timezone portion)
String original = '2012-11-09T00:00:00+0100'

// The format to read this input String
def inFormat = new java.text.SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssZ" )

// The format we want to output
def outFormat = new java.text.SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'" )
// Set the timezone for the output
outFormat.timeZone = java.util.TimeZone.getTimeZone( 'GMT' )

// Then parse the original String, and format the resultant
// Date back into a new String
String result = outFormat.format( inFormat.parse( original ) )

// Check it's what we wanted
assert result == '2012-11-08T23:00:00Z'

如果 TimeZone 中有 冒号,则您需要 Java 7 来执行此任务(或者可能需要像 JodaTime 这样的日期处理框架),您可以将前两行更改为:

// Your input String
String original = '2012-11-09T00:00:00+01:00'

// The format to read this input String (using the X
// placeholder for ISO time difference)
def inFormat = new java.text.SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssX" )

【讨论】:

  • 感谢这确实做了我需要做的事情。
猜你喜欢
  • 1970-01-01
  • 2017-04-19
  • 2019-03-17
  • 2011-08-29
  • 1970-01-01
  • 2018-07-28
  • 1970-01-01
  • 2010-12-24
  • 1970-01-01
相关资源
最近更新 更多