I believe that the following should fulfil your purpose.
String dateTimeString = "2020-04-30T09:59:00.272-05:00";
OffsetDateTime databaseDateTime = OffsetDateTime.parse(dateTimeString );
OffsetDateTime currentDateTime = OffsetDateTime.now(ZoneId.systemDefault());
if (databaseDateTime.isAfter(currentDateTime)) {
System.out.println("" + databaseDateTime + " is after " + currentDateTime);
} else {
System.out.println("" + databaseDateTime + " is before or equal to " + currentDateTime);
}
Output when I ran the code just now in my time zone (Europe/Copenhagen):
2020-04-30T09:59:00.272-05:00 is after 2020-04-26T21:48:36.331752+02:00
Since your string from the database contains a UTC offset (-05:00
) and no time zone (like America/New_York), I found it more appropriate to parse into an OffsetDateTime
. ZonedDateTime
would be overkill. For the local time I am passing ZoneId.systemDefault()
to the now
method of OffsetDateTime
. Comparing the two OffsetDateTime
objects with isAfter()
works nicely even if the offsets are different, this is taken into account. There are also methods isBefore
and isEqual
for comparison.
Stepping a step back, in most setups you should not be getting the date and time as a string from your database. Your JDBC 4.2 driver or your modern JPA implementation such as Hibernate 5 will be happy to fetch an OffsetDateTime
object from the database for you. See for example my answer here.