java - 检查日期在Java中的两个日期之间

标签 java date

<分区>

我想知道的一件事是如何计算从今天起 10 天后的日期。

第二件事是检查一个日期是否在另外两个日期之间。 例如,假设我有一个应用程序可以显示我在接下来的 10 天内需要做的事情(计划器)。现在我如何查看我分配给事件的日期是否在今天和距今天 10 天的日期之间?

最佳答案

使用 java.util.Datejava.util.Calendar 操作和比较日期非常痛苦,这就是为什么 JodaTime存在。到目前为止,没有一个答案涵盖了所讨论的时间。当日期具有非零时间时,比较可能会失败。还不清楚您是要进行包含 还是排除 比较。到目前为止发布的大多数答案都建议独家比较(即 5 月 24 日不是在 5 月 20 日和 5 月 24 日之间),而实际上将它设为更有意义包容性(即 5 月 24 日在 5 月 20 日和 5 月 24 日之间)。


One thing I want to know is how to calculate what date will it be 10 days from today.

使用标准的 Java SE 6 API,您需要 java.util.Calendar为此。

Calendar plus10days = Calendar.getInstance();
plus10days.add(Calendar.DAY_OF_YEAR, 10);

使用 JodaTime 你会这样做:

DateTime plus10days = new DateTime().plusDays(10);

Second thing is to check if one Date is between two other Dates. For example, let's say I have an app that shows what events I need to do in the next 10 days (planner). Now how can I see if the date I assigned to an event is between today and the date that is 10 days from today?

Calendar 是最糟糕的部分。我们先准备一下:

Calendar now = Calendar.getInstance();
Calendar plus10days = Calendar.getInstance();
plus10days.add(Calendar.DAY_OF_YEAR, 10);
Calendar event = Calendar.getInstance();
event.set(year, month - 1, day); // Or setTime(date);

要使用 Calendar#before()Calendar#after() 进行可靠比较,我们需要先去掉时间。假设现在是 2010 年 5 月 24 日上午 9 点,事件的日期设置为 2010 年 5 月 24 日,没有时间。当您想要包容性比较时,您希望在同一天让它返回 true。 IE。 (event.equals(now) || event.after(now)) 或 - 更短但同样 - (!event.before(now)) 应该返回 true .但实际上没有人这样做,因为 now 中存在时间。您需要先清除所有日历实例中的时间,如下所示:

calendar.clear(Calendar.HOUR);
calendar.clear(Calendar.HOUR_OF_DAY);
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);

或者,您也可以只比较日/月/年。

if (event.get(Calendar.YEAR) >= now.get(Calendar.YEAR)
    && event.get(Calendar.MONTH) >= now.get(Calendar.MONTH)
    && event.get(Calendar.DAY_OF_MONTH) >= now.get(Calendar.DAY_OF_MONTH)
{
    // event is equal or after today.
}

非常冗长。

使用 JodaTime,您只需使用 DateTime#toLocalDate()仅获取日期部分:

LocalDate now = new DateTime().toLocalDate();
LocalDate plus10days = now.plusDays(10);
LocalDate event = new DateTime(year, month, day, 0, 0, 0, 0).toLocalDate();
if (!event.isBefore(now) && !event.isAfter(plus10days)) {
    // Event is between now and 10 days (inclusive).
}

是的,以上就是您真正需要做的全部

关于java - 检查日期在Java中的两个日期之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2896173/

相关文章:

ruby - Rails 获取没有日期的当前时间

R:有光泽的dateRangeInput格式

java - 向现有 MimeMessage 添加附件

java - 将 onClickListener 设置为 Bottom Sheet 布局中的按钮

java - JPA 2 : How many methods are allowed in one entity with @Prepersist annotation?

bash - 在 awk 字符串中调用 'date' 命令,格式为 +%a

java - 添加到Arraylist会覆盖其余部分,这是为什么

java - Play-java 2.5.9 form.errorsAsJson() 总是返回英文错误信息

java - 在java中将日期转换为时间戳

android - 公历到回历(伊斯兰)日期