2012-09-26 108 views
0

我正在与SoupUI合作,我需要调整一个日期/时间(UTC),以便我回复GMT日期/时间。我回来的输入反应的日期看起来followes:在Groovy/Java中将UTC日期转换为GMT

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

我想将其转换为

2012-11-08T23:00:00Z 

不幸的是我缺乏的Java skils,因此也支持Groovy skils才能够做到这一点在我自己的。我做了很多日期转换搜索,但直到现在我仍然无法找到我正在寻找的东西。我会继续搜索。如果我设法得到解决方案,那么我会在这里发布。

+0

欢迎来到Stack Overflow!我们鼓励你[研究你的问题](http://stackoverflow.com/questions/how-to-ask)。如果你已经[尝试了某些东西](http://whathaveyoutried.com/),请将其添加到问题中 - 如果没有,请先研究并尝试您的问题,然后再回来。 – 2012-09-27 16:01:10

回答

3

假设没有在时区部分冒号,我认为这应该工作:

// 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' 

如果有在时区冒号,你需要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") 
+0

感谢这确实做了我需要它做的事情。 – user1700478