如何计算今天上午 00:00:00 的日期?
我需要计算今天开始的 java.util.Date (今天的上午 00:00:00)。有人知道比重置 java.util.Calendar 字段更好的事情吗:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.AM_PM, Calendar.AM);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
I need to calculate a java.util.Date for a beginning of a today day (00:00:00 a.m. of a today day). Does someone know something better than resetting fields of java.util.Calendar:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.AM_PM, Calendar.AM);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果您不关心时区,那么您的解决方案就可以。否则值得看看 JodaTime。
如果您最终决定切换到 JodaTime,那么您可以使用 DateMidnight 类应该在您的情况下使用。
If you don't bother about time zones then your solution is ok. Otherwise it's worth to look at JodaTime.
If you eventually decide to switch to JodaTime, then you can use DateMidnight class which is supposed to be used in your situation.
以下代码将返回当前日期的日历对象,时间为 00:00:00
它不会考虑时区值,并且与您的代码几乎相同。唯一的区别是它是在一行中将所有重置为 0。
The following code will return the current date's calendar object with time as 00:00:00
It will not consider the timezone values and is almost same as your code. Only difference is that it is done all resets to 0 in single line.
这个解决方案可以更好,因为它没有使用java的重元素Calender
This solution can be better as it does not make use of java's heavy element Calender
我在同一条船上,你提供的就是我的做法。我确实将它放在
DateUtil.stripToMidnight(...)
函数中...但是请记住在执行所有这些操作时考虑时区,因为此处的上午 0:00 在其他部分中不会相同世界的。
JodaTime 中可能有一种方法可以做到这一点,但我不知道。
I'm in the same boat, and what you have provided is how I do it. I do have it in a
DateUtil.stripToMidnight(...)
function...But just remember to consider TimeZones when doing all this, as 0:00am here, will not be the same in another part of the world.
There might be a way to do this in JodaTime, but I don't know of it.
使用 date4j 库:
With the date4j library :
无需额外库的另一种选择:
Another option without additional libraries:
从 java8 开始,假设您不关心时区,可以按如下方式完成
As of java8, it can be done as follow assuming you don't care about timezone