如果日期变量在特定时间之前,我必须检查。变量的格式为dd.MM.yyyy HH:mm:ss。
让我们今天拍摄日期31.10.2016 15:20:45。变量的值是30.10.2016 14:00:21。如果变量比今天大一天,如果时间早于或等于23:00,我该如何检查?
我尝试了以下代码。
Date today = new Date();
Calendar c = Calendar.getInstance();
c.setTime(causedAt);
c.add(Calendar.DATE, 1);
if (c.getTime().compareTo(today) < 0) { // It's more than 1 day.
setOneDayOverdue(true);
setFiveDaysOverdue(false);
}
但是使用此代码时,缺少时间的部分。
该解决方案应该适用于Java 7,并且不需要任何外部库,如Joda-Time。
答案 0 :(得分:3)
您应该使用新的Java 8 Date / Time API:
LocalDateTime NOW = LocalDateTime.now(); // e.g. 31.10.2016 15:20:45
// parse given Date/Time
LocalDateTime input = LocalDateTime.parse(strInput, DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"));
// Check if input is before "now"
boolean isBefore = input.isBefore(NOW);
请参阅https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html以获取满足您要求所需的所有方法。例如:
LocalDateTime yesterday = NOW.minusDays(1);
boolean isBeforeYesterday = input.isBefore(yesterday);
使用getHour()
和getMinute()
,您可以检查&lt; = 23:00。或者您可以使用LocalTime,但似乎这两个字段对您来说应该足够了。
答案 1 :(得分:1)
所以我得到了以下对我有用的代码:
public void setOverdueFlagIfRequired(Date today, Date causedAtDate) {
Calendar now = Calendar.getInstance();
now.setTime(today);
Calendar causedAt = Calendar.getInstance();
causedAt.setTime(causedAtDate);
Calendar yesterday2300 = Calendar.getInstance();
yesterday2300.setTime(today);
yesterday2300.add(Calendar.DATE, -1);
yesterday2300.set(Calendar.HOUR_OF_DAY, 23);
yesterday2300.set(Calendar.MINUTE, 0);
yesterday2300.set(Calendar.SECOND, 0);
yesterday2300.set(Calendar.MILLISECOND, 0);
Calendar fiveDaysBack2300 = Calendar.getInstance();
fiveDaysBack2300.setTime(yesterday2300.getTime());
fiveDaysBack2300.add(Calendar.DATE, -4);
if (causedAt.compareTo(fiveDaysBack2300)<=0) {
setFiveDaysOverdue(true);
}
else if (causedAt.compareTo(yesterday2300)<=0 && causedAt.compareTo(fiveDaysBack2300)>0) {
setOneDayOverdue(true);
}
}