Java时间在GMT [英] Java time in GMT

查看:343
本文介绍了Java时间在GMT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Grails应用程序,具有以下代码:

  Date now = Calendar.getInstance()。getTime()/ /也尝试新的Date()
printlnnow:+ now

当我做这个,我现在得到:8月18日12:47:09 CDT 2011 。我需要日期在GMT,而不是本地时间,因为我需要将GMT时间存储在数据库中。我可以使用一个simpleDateFormat对象来打印出格林尼治标准时间,但是我需要把它保存为GMT。



问题:我使用GMT将Date对象转换为Date对象?

解决方案

这突出了Java为什么会这样。以前的帖子都很接近,但是我们需要非常小心地获得当前GMT格式的时间,并获得当前CDT的时间和格林尼治标准时间。

  TimeZone reference = TimeZone.getTimeZone(GMT); 
日历myCal = Calendar.getInstance(reference);

这是GMT的当前时间,GMT的时区上下文。



要转换为保持区域完整的Date对象,您需要调用:

  TimeZone.setDefault(reference); 

此设置将持续与当前的JVM一样长。现在调用getTime应该产生所需的结果。

  myCal.getTime(); 


I have a Grails application with the following code:

Date now = Calendar.getInstance().getTime() //Also tried new Date()
println "now: " + now

When I do this, I get now: Thu Aug 18 12:47:09 CDT 2011. I need the date to be in GMT, not local time because I need to store the GMT time in a database. I can use a simpleDateFormat object to print out the time in GMT, but I need to actually store it as GMT.

Question: How do I convert a Date object to a Date object using GMT?

解决方案

This accentuates why Java sucks at time. The previous posts are all close, but we need to be very careful about getting the current time in GMT, and getting the current time in CDT and calling it GMT.

TimeZone reference = TimeZone.getTimeZone("GMT");
Calendar myCal = Calendar.getInstance(reference);

This is the current time in GMT, with a timezone context of GMT.

To convert to a Date object which keeps the zone intact you'll need to call:

TimeZone.setDefault(reference);

This setting will last as long as your current JVM. Now calling get Time should produce the desired result.

myCal.getTime();

这篇关于Java时间在GMT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆