Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two instances of "Instant" are on the same date in Java 8

I have two instances of the Instant class from java.time such as this:

Instant instant1 = Instant.now();
Instant instant2 = Instant.now().plus(5, ChronoUnit.HOURS);

Now I would like to check if the two instances of Instant are actually on the same date (day, month and year match). Easy I thought, let's just use the shiny new LocalDate and the universal from static method:

LocalDate localdate1 = LocalDate.from(instant1);
LocalDate localdate2 = LocalDate.from(instant2);

if (localdate1.equals(localdate2)) {
   // All the awesome
}

Except that universal from method is not so universal and Java complains at runtime with an exception:

java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: 2014-11-04T18:18:12Z of type java.time.Instant

Which leaves me back at square 1.

What is the recommended/fastest way check if two instances of Instant actually have the same date (have the same day, month, and year)?

like image 511
Robin Avatar asked Jan 15 '15 16:01

Robin


People also ask

How do you check if a date is within a date range in Java?

The idea is quite simple, just use Calendar class to roll the month back and forward to create a “date range”, and use the Date. before() and Date. after() to check if the Date is within the range.

How can I compare two datetime in Java?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.

How do you check if a date is after another date in Java?

The after() method is used to check if a given date is after another given date. Return Value: true if and only if the instant represented by this Date object is strictly later than the instant represented by when; false otherwise.


1 Answers

The Instant class does not work with human units of time, such as years, months, or days. If you want to perform calculations in those units, you can convert an Instant to another class, such as LocalDateTime or ZonedDateTime, by binding the Instant with a time zone. You can then access the value in the desired units.

http://docs.oracle.com/javase/tutorial/datetime/iso/instant.html

Therefore I suggest the following code:

LocalDate ld1 = LocalDateTime.ofInstant(instant1, ZoneId.systemDefault()).toLocalDate();
LocalDate ld2 = LocalDateTime.ofInstant(instant2, ZoneId.systemDefault()).toLocalDate();

if (ld1.isEqual(ld2)) {
    System.out.println("blubb");
}

Alternatively you could use

instant.atOffset(ZoneOffset.UTC).toLocalDate();
like image 171
flo Avatar answered Oct 25 '22 23:10

flo