Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a date is in previous x minutes?

I have an ISO String date like this one: 2019-12-17 15:14:29.198Z

I would like to know if this date is in the previous 15 minutes from now. Is-it possible to do that with SimpleDateFormat ?

val dateIso = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.FRENCH).parse(isoString)
like image 695
wawanopoulos Avatar asked Jan 27 '26 19:01

wawanopoulos


1 Answers

java.time.Instant

Use Instant class to represent a moment in UTC.

To parse, replace SPACE with a T per the ISO 8601 standard.

Instant instant = Instant.parse( "2019-12-17 15:14:29.198Z".replace( " " , "T" ) ;

Determine the current moment in UTC.

Instant now = Instant.now() ;

Determine 15 minutes ago. Call plus…/minus… methods for date-time math.

Instant then = now.minusMinutes( 15 ) ;

Apply your test. Here we use the Half-Open approach where the beginning is inclusive while the ending is exclusive.

boolean isRecent = 
    ( ! instant.isBefore( then ) )  // "Not before" means "Is equal to or later".
    && 
    instant.isBefore( now )         
;

For older Android, add the ThreeTenABP library that wraps the ThreeTen-Backport library. Android 26+ bundles java.time classes.

Table of which java.time library to use with which version of Java or Android

If you are doing much of this work, add the ThreeTen-Extra library to your project (may not be appropriate for Android, not sure). This gives you the Interval class and it’s handy comparison methods such as contains.

Interval.of( then , now ).contains( instant )
like image 90
Basil Bourque Avatar answered Jan 29 '26 08:01

Basil Bourque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!