How to compare Two date in android?

Viewed 13882

I have a date from server in the format yyyy-mm-dd HH:mm:ss .I have the current time in millis by System.currentTimeMillis(). I want to compare both dates and see if date received from server is future date and if it is so schedule an alarm for the future date. so my question how to compare this 2 different format dates and how to get remaining time (future- current) so as to schedule the alarm.

Edit: I already tried parsing the date in millis but it doesnt return value as same format as System.currentTimeMillis(). so it fails

2 Answers

I recommend you do it using the modern date-time API*.

A simple way to do it using the modern API is to parse the server's date-time string into ZonedDateTime using the server's timezone and convert the resulting object into Instant which you can compare with Instant#now.

Demo:

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // An arbitrary date for demo
        String strDateTime = "2021-05-09 10:20:30";

        // Replace JVM's default time zone, ZoneId.systemDefault() with applicable time
        // zone e.g. ZoneId.of("America/New_York")
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH)
                                    .withZone(ZoneId.systemDefault());

        ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);

        Instant instantServer = zdt.toInstant();
        Instant now = Instant.now();

        if (instantServer.isBefore(now))
            System.out.println("The server time is before the current time.");
        else if (instantServer.isAfter(now))
            System.out.println("The server time is after the current time.");
        else
            System.out.println("The server time is the same as the current time.");
    }
}

Output when I run it now in my system:

The server time is before the current time.

Learn more about the the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Related