在java中生成UTC时间

在java中生成UTC时间

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

问题描述

限时删除!!

我想将UTC 01/01/2100的UTC时间从Java中获取到2100-01-01 00:00:00。我正在2100-01-01 00:08:00。任何想法,如何纠正这个。

  public Date getFinalTime(){
日历日历= 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();
}


解决方案

您需要指定时间SimpleDateFormat的区域 - 目前正在解析本周时间的当地时间,这是UTC上午8点。

  TimeZone utc = TimeZone.getTimeZone(UTC); 
日历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);

从来没有,我个人建议使用,这是一般能力更强大。如果你愿意,我会很乐意将你的例子翻译成Joda Time。



此外,我看到你正在返回 calendar.getTime() - 就像您一次计算它一样返回 finalTime



ParseException 并继续执行,就好像没有发生一样是一个很糟糕的主意。我希望这只是示例代码,并不反映您的真实方法。同样,我假设真的你会解析一些其他的文本 - 如果没有,那么就像Eyal所说的那样,你应该调用 Calendar 直接。 (或者,再次使用Joda时间。)


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.

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();
}
解决方案

You need to specify the time zone for the SimpleDateFormat as well - currently that's parsing midnight local time which is ending up as 8am 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 Time which is far more capable in general. I'd be happy to translate your example into Joda Time if you want.

Additionally, I see you're returning calendar.getTime() - that's just the same as returning finalTime as soon as you've computed it.

Finally, just catching a ParseException and 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 really you'll be parsing some other text - if you're not, then as Eyal said, you should just call methods on Calendar directly. (Or, again, use Joda Time.)

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

1403页,肝出来的..

09-06 20:58