java 在java中生成UTC时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3366356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating UTC Time in java
提问by Boolean
I want to get the UTC time for 01/01/2100 in Java to '2100-01-01 00:00:00'. I am getting "2100-01-01 00:08:00". Any idea, how to correct this.
我想将 Java 中 01/01/2100 的 UTC 时间设为“2100-01-01 00:00:00”。我收到“2100-01-01 00:08:00”。任何想法,如何纠正这个。
public Date getFinalTime() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date finalTime = null;
try
{
finalTime = df.parse("01/01/2100");
} catch (ParseException e)
{
e.printStackTrace();
}
calendar.setTime(finalTime);
return calendar.getTime();
}
回答by Jon Skeet
You need to specify the time zone for the SimpleDateFormat as well - currently that's parsing midnight local timewhich is ending up as 8am UTC.
您还需要为 SimpleDateFormat 指定时区 - 目前正在解析当地时间午夜8 点 UTC。
TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(utc);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setTimeZone(utc);
Date finalTime = null;
try
{
finalTime = df.parse("01/01/2100");
} catch (ParseException e)
{
e.printStackTrace();
}
calendar.setTime(finalTime);
As ever though, I would personally recommend using Joda Timewhich is far more capable in general. I'd be happy to translate your example into Joda Time if you want.
和以往一样,我个人建议使用Joda Time,它通常功能更强大。如果您愿意,我很乐意将您的示例翻译成 Joda Time。
Additionally, I see you're returning calendar.getTime()- that's just the same as returning finalTimeas soon as you've computed it.
此外,我看到您正在返回calendar.getTime()- 这与finalTime计算后立即返回相同。
Finally, just catching a ParseExceptionand carrying on as if it didn't happen is a very bad idea. I'm hoping this is just sample code and it doesn't reflect your real method. Likewise I'm assuming that reallyyou'll be parsing some other text - if you're not, then as Eyal said, you should just call methods on Calendardirectly. (Or, again, use Joda Time.)
最后,只是抓住一个ParseException并继续进行就好像它没有发生一样是一个非常糟糕的主意。我希望这只是示例代码,并不能反映您的真实方法。同样,我假设您真的会解析一些其他文本 - 如果不是,那么正如 Eyal 所说,您应该直接调用方法Calendar。(或者,再次使用 Joda 时间。)
回答by Eyal Schneider
You need to set the time zone of the SimpleDateFormat object as well, otherwise it assumes the default time zone.
您还需要设置 SimpleDateFormat 对象的时区,否则它采用默认时区。
Anyway, it seems like using only a Calendar is enough in your case. Use its setters to set the right values for all fields (year, month, day, hour, etc), and then retrieve the time.
无论如何,在您的情况下,似乎只使用 Calendar 就足够了。使用其设置器为所有字段(年、月、日、小时等)设置正确的值,然后检索时间。

