You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ZonedDateTime与Calendar进行日期转换及增量操作的潜在异常问询

使用Calendar与ZonedDateTime的潜在计算差异与惯用性分析

我不确定使用Calendar对象相较于ZonedDateTime对象时,会出现哪些不可预见的影响,尤其是数据失效问题。我希望了解为何必须选择其中一种框架进行值的转换或解析。

我查阅了Java Tutorials中关于*"legacy date-time code"*的内容,但未找到可能出现失效的场景。

教程提及的以下几点均不在我的关注范围内:

"The Calendar class was not type safe".
我不关心类型安全,解析仅需几步操作。

"Because the classes were mutable, they could not be used in multithreaded applications".
可变状态并非我关注的话题。

"Bugs in application code were common due to the unusual numbering of months and the lack of type safety".
我不关心索引与枚举的差异。

以上几点均不构成选用某类的反例。


基础解析与格式化对比

使用SimpleDateFormat和Calendar

String string = "MMMM dd, yyyy '@' h:mm:ss a z";
SimpleDateFormat format = new SimpleDateFormat(string);
String value = "May 28, 2023 @ 6:50:01 pm EDT";
Calendar calendar = Calendar.getInstance();
calendar.setTime(format.parse(value));

打印代码:

System.out.println(calendar.getTimeInMillis());
System.out.printf("%tc", calendar.getTimeInMillis());

输出结果:

1685314201000
Sun May 28 18:50:01 EDT 2023

使用DateTimeFormatter和ZonedDateTime

(仅需将value中的"pm"改为大写,否则会抛出DateTimeParseException)

DateTimeFormatter format = DateTimeFormatter.ofPattern(string);
ZonedDateTime zonedDateTime = ZonedDateTime.parse(value, format);

打印代码:

System.out.println(zonedDateTime.toInstant().toEpochMilli());
System.out.printf("%tc%n", zonedDateTime.toInstant().toEpochMilli());
System.out.println(zonedDateTime);

输出结果:

1685314201000
Sun May 28 18:50:01 EDT 2023
2023-05-28T18:50:01-04:00[America/New_York]

对比两者数据,结果完全一致,均有效。


增量操作对比

以添加4小时(EDT为UTC-4)为例:

使用Calendar的add方法

calendar.add(Calendar.HOUR_OF_DAY, 4);

输出结果:

1685328601000
Sun May 28 22:50:01 EDT 2023

使用ZonedDateTime的plusHours方法

zonedDateTime = zonedDateTime.plusHours(4);

输出结果:

1685328601000
Sun May 28 22:50:01 EDT 2023
2023-05-28T22:50:01-04:00[America/New_York]

两者结果再次一致。计算时间差:1685328601000 - 1685314201000 = 14400000,等价于4小时的毫秒数。


核心疑问

基于以上基础解析和增量操作的结果,我想知道:

  • 使用其中一类时会产生哪些未预见的计算错误?例如两者的年份测量精度是否存在差异(如365.25天与365.2425天)?
  • 除Java官方提及的设计问题外,从哲学层面而非范式层面来看,哪类更具惯用性?

内容的提问来源于stack exchange,提问作者Reilas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 10:22:03