Compare two dates without taking into account time
I have a date in timestamp
format. How can I check whether it is equal to the current date without taking into account the time? For example, 1502010000
it is equal to 6.07.2017
.
I got this date and the current one, but how to compare it is not clear:
Instant date= Instant.ofEpochSecond(1502010000);
Instant now = Instant.now();
2 answers
Java 8 introduced a new mechanism for working with dates implemented by the API from the java.time.*
package.
In this case, you can use the following behavior layout to compare dates:
Timestamp timestamp = new Timestamp(1502010000);
LocalDateTime before = timestamp.toLocalDateTime();
LocalDateTime now = LocalDateTime.now();
int compareREsult = now.compareTo(before);
If compareResult
is a negative number - if the date being compared is later, a positive number - if earlier, and zero if equal.
UPD:
Since there is an unaccounted condition in the question that the date should be compared without the time, the following option is suggested:
Timestamp timestamp = new Timestamp(1502041448453l);
// System.out.println(timestamp); выведет "2017-08-06 20:44:08.453"
LocalDate localDateTime = timestamp.toLocalDateTime().toLocalDate();
LocalDate now = LocalDate.now();
// System.out.println(now); выведет "2017-08-06"
// Выведет 0;
System.out.println(now.compareTo(localDateTime));
I may not understand something, but:
Https://habrahabr.ru/post/61391/
TIMESTAMP Stores a 4-byte integer equal to the number of seconds, since midnight on January 1, 1970
And the number you give is January 18, 1970, and not August 6, 2017
Http://www.fileformat.info/tip/java/date2millis.htm
But if you have everything perfectly shows, then you can use Calendar and just reset it to zero time
private static Date dateRemoveTime(Date date){
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}