Java:这是将当前时间作为特定时区的日历对象获取的正确方法吗?

Java:这是将当前时间作为特定时区的日历对象获取的正确方法吗?,java,calendar,timezone,Java,Calendar,Timezone,我知道还有其他类似的问题,但我想出了自己的方法来获取特定时区的当前时间,所以我只想确认它是否正确,或者是否存在我没有注意到的问题 Calendar cal = Calendar.getInstance(); // Assuming we want to get the current time in GMT. TimeZone tz = TimeZone.getTimeZone("GMT"); cal.setTimeInMillis(calendar.getTimeInMillis()

我知道还有其他类似的问题,但我想出了自己的方法来获取特定时区的当前时间,所以我只想确认它是否正确,或者是否存在我没有注意到的问题

Calendar cal = Calendar.getInstance();

// Assuming we want to get the current time in GMT.
TimeZone tz = TimeZone.getTimeZone("GMT");
cal.setTimeInMillis(calendar.getTimeInMillis()
                    + tz.getOffset(calendar.getTimeInMillis())
                    - TimeZone.getDefault().getOffset(calendar.getTimeInMillis()));

// Calendar should now be in GMT.

上面的说法完全正确吗?我做了我自己的测试,它看起来像预期的那样工作,但我只是想再次与堆栈溢出方面的专家确认一下。

我更喜欢使用joda时间,而不是那样


检查。

如果您只是使用时区参数执行
日历.getInstance
,则
get()
方法的日历内部状态将返回该时区的时间字段。例如:

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    // if i run this at 9 EST this will print 2
    System.out.println(cal.get(Calendar.HOUR)); 
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    System.out.println(sdf.format(new Date()));
如果您只需要显示本地时间,可以在format对象上设置
时区。例如:

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    // if i run this at 9 EST this will print 2
    System.out.println(cal.get(Calendar.HOUR)); 
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    System.out.println(sdf.format(new Date()));

就像Macarse所说的,如果你需要做更复杂的事情,Joda time就是你的位置。Java date API真是一场噩梦。

当然,我听说过很多关于joda time的好消息,但我目前只限于Sun的Java中提供的内容。不过还是要谢谢你,我一定会在不久的将来试一试。你到底需要它做什么?基本上,日历中的timeInMillis值总是以GMT为单位,因此通常不需要使用timeInMillis和GMT偏移量进行计算。如果需要在特定时区中获取值(如使用calendar.get()获取日期或时间),只需通过calendar.setTimeZone()设置时区,然后获取特定于该时区的值。如果仅出于显示目的,也可以直接在DateFormat上设置时区。