3

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)
wawanopoulos
  • 9,614
  • 31
  • 111
  • 166

3 Answers3

4

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 )
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

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;
}
Ev0lv3zz
  • 58
  • 8
  • 1
    FYI, the terribly flawed date-time classes such as [`java.util.Date`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/tutorial/datetime/TOC.html) classes built into Java 8 and later. – Basil Bourque Jan 01 '20 at 04:38
-1

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");
}