我正在尝试使用以下代码来理解行为。我的本地时区是 UTC -7(亚利桑那州)。
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE,40);
cal.set(Calendar.AM_PM,Calendar.PM);
System.out.println("1 UTC -4 Hour:" + cal.get(Calendar.HOUR_OF_DAY));
System.out.println("1 UTC -4 Day:" + cal.get(Calendar.DAY_OF_MONTH));
System.out.println("1 UTC -7 Time Stamp:" + cal.getTime().toString());
cal.set(Calendar.HOUR,12);
System.out.println("2 UTC -4 Hour:" + cal.get(Calendar.HOUR_OF_DAY));
System.out.println("2 UTC -4 Day:" + cal.get(Calendar.DAY_OF_MONTH));
System.out.println("2 UTC -7 Time Stamp:" + cal.getTime().toString());
cal.setTimeZone(TimeZone.getTimeZone("America/New_York")); //set time zone to UTC -4
System.out.println("3 UTC -4 Hour:" + cal.get(Calendar.HOUR_OF_DAY));
System.out.println("3 UTC -4 Day:" + cal.get(Calendar.DAY_OF_MONTH));
System.out.println("3 UTC -7 Time Stamp:" + cal.getTime().toString());
cal.set(Calendar.HOUR,12);
System.out.println("4 UTC -4 Hour:" + cal.get(Calendar.HOUR_OF_DAY));
System.out.println("4 UTC -4 Day:" + cal.get(Calendar.DAY_OF_MONTH));
System.out.println("4 UTC -7 Time Stamp:" + cal.getTime().toString());
它生成以下输出:
1 UTC -4 小时:12
1 UTC -4 日:27
1 UTC -7 时间戳:2011 年 9 月 27 日星期二 12:40:37 MST
2 UTC -4 小时:0
2 UTC -4 日:28
2 UTC -7 时间戳:Wed Sep 28 00:40:37 MST 2011
3 UTC -4 Hour:3
3 UTC -4 Day:28
3 UTC -7 时间戳:Wed Sep 28 00:40:37 MST 2011
4 UTC -4 Hour:12
4 UTC -4 Day:28
4 UTC -7 时间戳:Wed Sep 28 09:40:37 MST 2011
我不明白为什么第一个 cal.set(Calendar.HOUR,12) 会导致日期翻转到第二天。对一个值使用 add() 会导致调整其他值是有道理的,但 set() 也这样做没有意义。
有没有办法在保留所有其他值的情况下进行绝对 set()?