为什么 java.util.Date 的 setTime() 方法没有被弃用?
所有其他修改器在 JDK 1.1 中都已被弃用,那么为什么 setTime()
保持原样呢?当然,java.util.Calendar
- 操作日期的正确方法 - 可以根据需要使用 java.util.Date 创建
构造函数?java.util.Date
的新实例(长)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
已弃用的
Date
位是与日历相关的位(即日、月、年等)。您会注意到,日历字段的访问器方法也被弃用,而不仅仅是修改器。然而,毫秒值的表示形式仍然是
Date
的工作方式,并且与日历表示形式无关,因此它仍然未弃用。The bits of
Date
that were deprecated were those bits that related to calendars (i.e. day, month, year, etc). You'll note that the accessor methods for calendar fields are also deprecated, not just the mutators.The representation as a milliseconds value, however, is still the way
Date
works, and is unrelated to the calendar representation, so it stayed as undeprecated.其他变异器尝试使用 java.util.Date 作为日历,而不是作为时间的瞬间,自 1970 年 1 月 1 日凌晨 12 点(UTC)以来的毫秒数。因此,不弃用该变异器是有道理的。
当然,
Date
/Calendar
API 仍然很糟糕,您仍然应该使用 Joda Time 尽可能 - 但我明白为什么这个调用没有被弃用。你不能在事后使类型不可变,这不是弃用的重点 - 重点是试图阻止人们使用它作为“1976 年 6 月 19 日”等的存储。The other mutators were trying to use
java.util.Date
as a calendar, rather than as an instant in time, wrapping a number of milliseconds since Jan 1st 1970 12am UTC. As such, it makes sense for that one mutator not to be deprecated.The
Date
/Calendar
APIs are still terrible of course, and you should still use Joda Time wherever possible - but I can see why that call wasn't deprecated. You can't make a type immutable after the fact, and that wasn't the point of the deprecation - the point was to try to stop people from using it as storage for "June 19th 1976" etc.因为
setTime
方法至少在逻辑上是正确的:需要 day、month 等的setX
方法没有任何意义:javaDate
是一个时间,因此是日、小时、月 > 等仅与特定TimeZone
中该Date
的视图相关。Because the
setTime
method is at least logically correct: thesetX
methods which take day, month etc make no sense: a javaDate
is an instant in time and hence day, hour, month etc relate only to the view of thatDate
in a particularTimeZone
.