且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-18 23:27:57

在 Java 中,日期在内部表示为自纪元以来的 UTC 毫秒(因此不考虑时区,这就是为什么您得到与 getTime() 为您提供提到的毫秒数.
在您的解决方案中:

In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime() gives you the mentioned milliseconds).
In your solution:

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 的偏移量添加到指定的时区(在您的示例中为亚洲/加尔各答"),以毫秒为单位,因此这应该可以正常工作.

you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.

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

Another possible solution would be to utilise the static fields of the Calendar class:

//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);

参考 ***.com/questions/7695859/ 更深入的解释.

Refer to ***.com/questions/7695859/ for a more in-depth explanation.