一个奇怪的异常
@Test public void case2(){ Calendar c = Calendar.getInstance(); c.set(2023, 11-1, 8, 15, 23, 17); // int y1 = c.get(Calendar.YEAR); // int M1 = c.get(Calendar.MONTH) + 1; // int d1 = c.get(Calendar.DAY_OF_MONTH); // int H1 = c.get(Calendar.HOUR_OF_DAY); // int m1 = c.get(Calendar.MINUTE); // int s1 = c.get(Calendar.SECOND); // int S1 = c.get(Calendar.MILLISECOND); c.setTimeZone(TimeZone.getTimeZone("America/New_York")); int y = c.get(Calendar.YEAR); int M = c.get(Calendar.MONTH) + 1; int d = c.get(Calendar.DAY_OF_MONTH); int H = c.get(Calendar.HOUR_OF_DAY); int m = c.get(Calendar.MINUTE); int s = c.get(Calendar.SECOND); int S = c.get(Calendar.MILLISECOND); System.out.println(y+"-"+M+"-"+d+" "+H+":"+m+":"+s); }
输出结果:2023-11-8 15:23:17
将上例中的注释代码,任选一行或多行,取消掉它的注释,输出结果为:2023-11-8 2:23:17
想知道原因?
7
收起
正在回答 回答被采纳积分+1
1回答
好帮手慕小尤
2023-11-08 15:40:42
同学你好,这与时区有关系,因我们设置了时区,当两次时区不一致是就会出现问题,同学可以尝试将代码移动到 c.setTimeZone(TimeZone.getTimeZone("America/New_York"));下面,就不会出现该问题了。如下所示:
Calendar c = Calendar.getInstance(); c.set(2023, 11-1, 8, 15, 23, 17); c.setTimeZone(TimeZone.getTimeZone("America/New_York")); // int y1 = c.get(Calendar.YEAR); // int M1 = c.get(Calendar.MONTH) + 1; // int d1 = c.get(Calendar.DAY_OF_MONTH); // int H1 = c.get(Calendar.HOUR_OF_DAY); // int m1 = c.get(Calendar.MINUTE); int s1 = c.get(Calendar.SECOND); int S1 = c.get(Calendar.MILLISECOND); int y = c.get(Calendar.YEAR); int M = c.get(Calendar.MONTH) + 1; int d = c.get(Calendar.DAY_OF_MONTH); int H = c.get(Calendar.HOUR_OF_DAY); int m = c.get(Calendar.MINUTE); int s = c.get(Calendar.SECOND); int S = c.get(Calendar.MILLISECOND); System.out.println(y+"-"+M+"-"+d+" "+H+":"+m+":"+s);
祝学习愉快!
Java工程师 2024版
- 参与学习 2020 人
- 提交作业 1249 份
- 解答问题 1202 个
2024重磅革新,超百小时内容豪华升级,加速提升高级技能与高薪就业竞争力 课程紧贴企业最新人才需求,历经7年持续迭代,帮助万名学子入行转行 从零起点到高阶实战,学习路径稳健顺滑,成就从小白到工程师高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星