Reputation: 9804
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)
Upvotes: 3
Views: 4027
Reputation: 339372
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.
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 )
Upvotes: 4
Reputation: 58
If you already know the reference date everytime you access the program, you can use java.util.Calendar.
boolean isBefore;
long timeToCheck = 15*60*1000; //15 minutes.
Calendar calendar = Calendar.getInstance(), calendar2 = Calendar.getInstance();
calendar.set(Calendar.DATE, yourDay);
calendar.set(Calendar.HOUR_OF_DAY, yourHour);
calendar.set(Calendar.MINUTE, yourMinute);
calendar.set(Calendar.SECOND, yourSecond);
if (calendar.before(calendar2)){
long timeInMillis = calendar2.getTimeInMillis() - calendar.getTimeInMillis();
if ( timeInMillis >= timeToCheck ) isBefore = true;
else isBefore = false;
}
Upvotes: 0
Reputation: 9
Is this you want:
int xMinutes = 10 * 60 * 1000;
long dateIsoinMillis = dateIso.getTime();
long xMinsAgo = System.currentTimeMillis() - xMinutes;
if (dateIsoinMillis < xMinsAgo) {
System.out.println("searchTimestamp is older than 10 minutes");
}
Upvotes: -1