1

I want to find difference between 2 timestamps. What I am doing is storing 1st timestamp in shared prefs and try to subtractt it from the new timestamp. To get timestamp, I am using -

public static String setTimestamp() {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            return dateFormat.format(new Date());
        } catch (Exception e) {
            return null;
        }
} 

How do I subtract 2 timestamps and check if the difference is smaller than 120 seconds?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Monique890
  • 93
  • 1
  • 7
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Apr 16 '18 at 08:09
  • What did your search bring up? Might you for example have found [this question: Calculate date/time difference in java](https://stackoverflow.com/questions/5351483/calculate-date-time-difference-in-java). There are lots of similar questions out there, no need to ask your own. – Ole V.V. Apr 16 '18 at 08:15
  • Possible duplicate of [In Java, how do I get the difference in seconds between 2 dates?](https://stackoverflow.com/questions/1970239/in-java-how-do-i-get-the-difference-in-seconds-between-2-dates) – Ole V.V. Apr 16 '18 at 08:17
  • Is the timestamp in the shared preferences a string in `yyyy-MM-dd HH:mm:ss` format too? That would be fragile if you don’t know what was the time zone setting of the device when the string was saved. – Ole V.V. Apr 16 '18 at 08:34

2 Answers2

2

You can find difference like this

long diffInMs = firstTimestamp - secondTimestamp;

long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);

Now you have got difference in seconds so just go ahead and check your condition

if(diffInSec < 120){

}
Akshay Panchal
  • 695
  • 5
  • 15
1

I suggest the following for getting a string for saving into your shared preferences:

    String timestampToSave = Instant.now().toString();

Now to count the seconds since the time given in that string:

    String timestampFromSharedPreferences = mySharedPrefs.getString(KEY, null);
    long diffInSeconds = Duration.between(Instant.parse(timestampFromSharedPreferences),
                                            Instant.now())
            .getSeconds();
    if (diffInSeconds < 120) {
        System.out.println("Less than 120");
    }

An Instant is an unambiguous point in time independent of time zone. Its string representation goes like 2018-04-16T09:26:27.929Z (ISO 8601). The Z in the end means UTC. So the above works even in the off case where the user changes the time zone setting of the device, or some other part of your program changes the time zone setting of your JVM. You notice that we do not need an explicit formatter for formatting the string and parsing it back into an Instant.

In case you want to compare to 2 minutes rather than 120 seconds, use toMinutes() instead of getSeconds().

In case you cannot change the string saved in shared preferences, you will need to cross you fingers that the time zone setting hasn’t been changed and then parse the string like this:

    DateTimeFormatter timestampFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    Instant storedTimestamp = LocalDateTime.parse(timestampFromSharedPreferences, timestampFormatter)
            .atZone(ZoneId.systemDefault())
            .toInstant();

Now let Duration calculate the difference between the Instant objects as before.

I am using and recommending java.time, the modern Java date and time API. The SimpleDateFormat class that you were using is long outdated along with Date and is also notoriously troublesome. The modern API is so much nicer to work with.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161