比较 java 中的日期。搜索今天,明天
Comparing dates in java. Search today, tomorrow
我接受 JSP 页面的属性并想比较。传递给 servlet 的日期是今天、明天还是另一天。我该如何比较这个???
Date dateToDo = Date.valueOf(request.getParameter("date")); //for example 2019-08-31
Date today = new Date (System.currentTimeMillis());
Date tomorrow = new Date (System.currentTimeMillis() + 86400000);
if(dateToDo.equals(today)){
System.out.println("Today!");
} else if (dateToDo.equals(tomorrow)){
System.out.println("Tomorrow!");
} else {
System.out.println("OTHER DAY");
}
java.time
LocalDate dateToDo = LocalDate.parse(request.getParameter("date")); //for example 2019-08-31
LocalDate today = LocalDate.now(ZoneId.of("Europe/Minsk"));
LocalDate tomorrow = today.plusDays(1);
if(dateToDo.equals(today)){
System.out.println("Today!");
} else if (dateToDo.equals(tomorrow)){
System.out.println("Tomorrow!");
} else {
System.out.println("OTHER DAY");
}
不要使用 java.sql.Date
。首先,它的设计很糟糕,确实是一个糟糕的黑客攻击,而且早就过时了。其次,除了将日期传入和传出 SQL 数据库之外,它从来没有其他用途。第三,虽然它假装只是一个没有时间的日期,但实际上它不是,而是在内部存储毫秒精度,这导致其 equals
方法无法按预期工作。相反,我使用 java.time 中的 LocalDate
,现代 Java 日期和时间 API。 LocalDate
是您所需要的:没有时间和时区的日期。
Link: Oracle tutorial: Date Time 解释如何使用 java.time.
我接受 JSP 页面的属性并想比较。传递给 servlet 的日期是今天、明天还是另一天。我该如何比较这个???
Date dateToDo = Date.valueOf(request.getParameter("date")); //for example 2019-08-31
Date today = new Date (System.currentTimeMillis());
Date tomorrow = new Date (System.currentTimeMillis() + 86400000);
if(dateToDo.equals(today)){
System.out.println("Today!");
} else if (dateToDo.equals(tomorrow)){
System.out.println("Tomorrow!");
} else {
System.out.println("OTHER DAY");
}
java.time
LocalDate dateToDo = LocalDate.parse(request.getParameter("date")); //for example 2019-08-31
LocalDate today = LocalDate.now(ZoneId.of("Europe/Minsk"));
LocalDate tomorrow = today.plusDays(1);
if(dateToDo.equals(today)){
System.out.println("Today!");
} else if (dateToDo.equals(tomorrow)){
System.out.println("Tomorrow!");
} else {
System.out.println("OTHER DAY");
}
不要使用 java.sql.Date
。首先,它的设计很糟糕,确实是一个糟糕的黑客攻击,而且早就过时了。其次,除了将日期传入和传出 SQL 数据库之外,它从来没有其他用途。第三,虽然它假装只是一个没有时间的日期,但实际上它不是,而是在内部存储毫秒精度,这导致其 equals
方法无法按预期工作。相反,我使用 java.time 中的 LocalDate
,现代 Java 日期和时间 API。 LocalDate
是您所需要的:没有时间和时区的日期。
Link: Oracle tutorial: Date Time 解释如何使用 java.time.