如何更改 java.util.Calendar/Date 的 TIMEZONE

新手上路,请多包涵

我想在运行时更改 Java 日历实例中的 TIMEZONE 值。我在下面试过。但是两种情况下的输出是相同的:

     Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    System.out.println(cSchedStartCal.getTime().getTime());
    cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
    System.out.println(cSchedStartCal.getTime().getTime());

输出:

1353402486773

1353402486773

我也试过这个,但输出仍然是一样的:

     Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    System.out.println(cSchedStartCal.getTime());

    Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
    cSchedStartCal1.setTime(cSchedStartCal.getTime());
    System.out.println(cSchedStartCal.getTime());

在 API 中,我看到了以下评论,但我无法理解其中的大部分内容:

      * calls: cal.setTimeZone(EST); cal.set(HOUR, 1); cal.setTimeZone(PST).
     * Is cal set to 1 o'clock EST or 1 o'clock PST?  Answer: PST.  More
     * generally, a call to setTimeZone() affects calls to set() BEFORE AND
     * AFTER it up to the next call to complete().

请你帮助我好吗?

一种可能的解决方案:

     Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    long gmtTime = cSchedStartCal.getTime().getTime();

    long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
    Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
    cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);

这个解决方案好吗?

原文由 Kanagavelu Sugumar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 696
1 个回答

在 Java 中,日期在内部以自纪元以来的 UTC 毫秒表示(因此不考虑时区,这就是为什么您会得到相同的结果,因为 getTime() 为您提供了提到的毫秒)。

在您的解决方案中:

 Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();

long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);

您只需将 GMT 的偏移量添加到指定的时区(在您的示例中为“亚洲/加尔各答”),以毫秒为单位,所以这应该可以正常工作。

另一种可能的解决方案是利用 Calendar 类的静态字段:

 //instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);

有关更深入的说明,请参阅 stackoverflow.com/questions/7695859/

原文由 KeyNone 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题