本文介绍了Java GregorianCalendar更改TimeZone的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置HOUR_OF_DAY字段并更改GregorianCalendar日期对象的时区.

I'm trying to set HOUR_OF_DAY field and change Timezone of the GregorianCalendar date object.

GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT+10"));
System.out.println("HOUR: " + date.get(Calendar.HOUR_OF_DAY));
date.set(Calendar.HOUR_OF_DAY, 23);
//date.get(Calendar.HOUR_OF_DAY);
date.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("HOUR: " + date.get(Calendar.HOUR_OF_DAY));

输出:

HOUR: 16
HOUR: 23

出于某些原因,设置了不同的时区后,HOUR_OF_DAY的值不会更改.但是,如果我取消对HOUR_OF_DAY的date.get的注释,一切都会按预期进行

For some reason value of HOUR_OF_DAY does not change after setting different timezone. But if I uncomment date.get for HOUR_OF_DAY, everything works exactly as it should

GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT+10"));
System.out.println("HOUR: " + date.get(Calendar.HOUR_OF_DAY));
date.set(Calendar.HOUR_OF_DAY, 23);
date.get(Calendar.HOUR_OF_DAY); // uncommenting this line will is changing the output
date.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("HOUR: " + date.get(Calendar.HOUR_OF_DAY));

输出:

HOUR: 16
HOUR: 13

这怎么可能?为什么.get方法会更改对象行为?

How is this possible? Why .get method is changing object behaviour?

推荐答案

GregorianCalendar 类继承其 Calendar 中的 get 方法,具有以下副作用:

The GregorianCalendar class inherits its get method from Calendar, which has the following side effect:

这意味着在 Calendar 对象上调用 get 时,将重新计算 time 值和所有字段.这可能导致某些不可预测的行为,特别是与 setTimeZone 结合使用时,该行为具有某些已记录的越野车行为.

This means that the time value and all fields are recomputed when get is called on a Calendar object. This can lead to some unpredictable behavior, particularly when coupled with setTimeZone, which has some documented buggy behavior of its own.

这篇关于Java GregorianCalendar更改TimeZone的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:30
查看更多