How to compare two dates along with time in java

后端 未结 6 1599
独厮守ぢ
独厮守ぢ 2020-11-29 07:30

I have two Date objects with the below format.

SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd\'T\'HH:mm:ss\");
String         


        
6条回答
  •  长情又很酷
    2020-11-29 08:03

    The other answers are generally correct and all outdated. Do use java.time, the modern Java date and time API, for your date and time work. With java.time your job has also become a lot easier compared to the situation when this question was asked in February 2014.

        String dateTimeString = "2014-01-16T10:25:00";
        LocalDateTime dateTime = LocalDateTime.parse(dateTimeString);
        LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
    
        if (dateTime.isBefore(now)) {
            System.out.println(dateTimeString + " is in the past");
        } else if (dateTime.isAfter(now)) {
            System.out.println(dateTimeString + " is in the future");
        } else {
            System.out.println(dateTimeString + " is now");
        }
    

    When running in 2020 output from this snippet is:

    2014-01-16T10:25:00 is in the past

    Since your string doesn’t inform of us any time zone or UTC offset, we need to know what was understood. The code above uses the device’ time zone setting. For a known time zone use like for example ZoneId.of("Asia/Ulaanbaatar"). For UTC specify ZoneOffset.UTC.

    I am exploiting the fact that your string is in ISO 8601 format. The classes of java.time parse the most common ISO 8601 variants without us having to give any formatter.

    Question: For Android development doesn’t java.time require Android API level 26?

    java.time works nicely on both 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) the modern API comes built-in.
    • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern 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

    • Oracle tutorial: Date Time explaining how to use java.time.
    • Java Specification Request (JSR) 310, where java.time was first described.
    • ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
    • ThreeTenABP, Android edition of ThreeTen Backport
    • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
    • Wikipedia article: ISO 8601

提交回复
热议问题