从 java.util.date 获取日期的简洁方法
我试图仅从 java.util.date
检索日期。我知道我可以将时间设置为 0,但如果可能的话,我正在寻找一种更干净、更简洁的方法。这存在吗?
谢谢! Krt_马耳他
I'm trying to retrieve the date only from a java.util.date
. I know I can set the time to 0 but I'm searching for a cleaner, more concise way if possible. Does this exist?
Thanks!
Krt_Malta
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更简洁的方法是使用 Joda Time 开始,其中有 LocalDate、LocalTime、LocalDateTime 的单独概念、DateTime、Instant 等。
您可以在 java.util.Date 和 Joda 类型之间进行翻译,但我建议您坚持使用 Joda 来处理尽可能多的代码,并且仅在以下情况下进行翻译你真的需要这样做。
抱歉,如果您希望避免使用额外的库,但 Joda 比内置 API 好得多,在我看来,这是非常值得投资的。请注意,在 Java 类型中,您需要确定您感兴趣的时区 - java.util.Date 定义一个时间点,根据您的时区,该时间点可能会出现在世界各地多达三个不同的日期。
The cleaner way is to use Joda Time to start with, where there are separate concepts of LocalDate, LocalTime, LocalDateTime, DateTime, Instant etc.
You can translate between java.util.Date and the Joda types, but I would suggest you stick to using Joda for as much of the code as you can, and only translate when you really need to.
Sorry if you'd hoped to avoid an extra library - but Joda is so much better than the built-in API, it's well worth investing in the effort IMO. Note that within the Java types you'll need to determine which time zone you're interested in - java.util.Date defines an instant in time, which may occur in as many as three different dates around the world depending on your time zone.
另一个选项是
DateUtils
库中的truncate
方法。您输入您感兴趣的日期和字段(在本例中为CALENDAR.DAY_OF_MONTH
)。其余的将设置为 0。有效:完成工作。
有关该方法的更多信息位于: http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/time/DateUtils.html#truncate%28java.lang.Object, %20int%29
Another option is the
truncate
method in theDateUtils
library. You put in the date and the field up to which you are interested (in this caseCALENDAR.DAY_OF_MONTH
). The rest will be set to 0. Effectively:did the job.
More info about the method is at: http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/time/DateUtils.html#truncate%28java.lang.Object,%20int%29