--I want to find out if the date to be checked is before, after, or on the day of today.
--However, the date to be checked is 00:00:00, so I want to compare only the dates.
--Today's date generated by new Date ()
is up to the time
--By comparison, even if the dates are the same, if the times are different, it will not be judged on the day.
--Compare before and after using the method of java.util.Date
--Use the well-known DateUtils
from ʻorg.apache.commons.lang3`
UseMethod
java.util.Date.equals(Object obj)
java.util.Date.before(Date when)
java.util.Date.after(Date when)
org.apache.commons.lang3.time.DateUtils.truncate(Date date, int field)
DateUtilService.java
public void printDate(Date targetDate) {
//00 today:00:Get 00
Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
if (targetDate.equals(today)) {
System.out.println("It's today.");
} else if (targetDate.after(today)) {
System.out.println("It is a date after today.");
} else if (targetDate.before(today)) {
System.out.println("It is a date before today.");
}
}
DateUtils.truncate
Calendar.DAY_OF_MONTH
as the second argumentDateUtils.isSameDay
If it's just the day or not, you can use DateUtils.isSameDay
to compare only the dates and return a boolean without truncate at 00:00:00.
You can change the position to zero depending on the variable passed to the second argument of DateUtils.truncate
.
int field | Position to be zero |
---|---|
Calendar.DAY_OF_MONTH | 00:00:00 |
Calendar.HOUR_OF_DAY | XX:00:00 |
Calendar.MONTH | 00 a day:00:00 |
Calendar.YEAR | 1/1 00:00:00 |
[Java] How to truncate the hour, minute, and second of Date Class DateUtils|org.apache.commons.lang3.time
Recommended Posts