Ammad Ammad - 2 months ago 18
Java Question

How to find date values which are more than 10 days old

I am using Java and iterating over D.B. column which in return gives me date and time string as shown below:

String dateTime = resultSet.getSeries().get(0).getValues().get(0).get(0);

If I iterate on this resultset I am getting dateTime values in format as shown below.


Out of these records, how can I compare date string with "current" date object and discard those values which are more than 10 days old?

Answer Source


Retrieve date-time values as date-time objects, not strings.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.

Instant instant = myResultSet.getObject( … , Instant.class ) ;

Compare to ten days before the current moment.

Instant now = ;
Instant tenDaysAgo = now.minus( 10 , ChronoUnit.DAYS ) ;
Boolean prior = instant.isBefore( tenDaysAgo ) ;

You may not want to base your "ten days ago" on UTC. If not, apply a time zone to get a ZonedDateTime and LocalDate. This has been covered many times so search Stack Overflow. Think about if "days" means (a) chunks of 24-hours or (b) calendar dates to you.

FYI, those strings happen to be in standard ISO 8601 format. The T separates the date portion from time portion. The Z is short for Zulu and means UTC. This Instant class uses the same format in its toString method.


Generally, you should do such comparison work in the database as part of the SQL query rather than in your Java app. The database is highly tuned for this work; your app is not.

String sql = "SELECT * FROM tbl_ WHERE when_ < ? " ;
… make your PreparedStatement
myPreparedStatement.setObject( 1 , tenDaysAgo ) ;
… execute