Android difference between two dates in seconds

后端 未结 4 1363
离开以前
离开以前 2020-12-24 05:16

I\'ve tried different methods around the web but couldn\'t make it work.

Cursor cursor = sqlite.myDataBase.rawQuery(\"SELECT StartDate, EndDate FROM Tracks          


        
4条回答
  •  囚心锁ツ
    2020-12-24 05:57

    While the other answers work and were fine answers in 2010, I am providing the modern answer.

    java.time and ThreeTenABP

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
        ZoneId zone = ZoneId.systemDefault();
    
        String startDateString = "2019-12-31 23:34:45";
        String endDateString = "2020-01-01 07:56:34";
    
        ZonedDateTime start = LocalDateTime.parse(startDateString, formatter).atZone(zone);
        ZonedDateTime end = LocalDateTime.parse(endDateString, formatter).atZone(zone);
    
        long diffSeconds = ChronoUnit.SECONDS.between(start, end);
    
        System.out.println("Difference: " + diffSeconds + " seconds");
    

    In most time zones output from this snippet will be:

    Difference: 30109 seconds

    I am using ZonedDateTime because it takes transitions to and from summer time (DST) and other time anomalies into account. It requires that you use the correct time zone, of course. If the time zone setting of your device is changed since you stored the dates and times into your database, you risk some surprises. To prevent such, you may store a UTC offset along with your times and then parse them into OffsetDateTime on retrieval.

    Question: 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.

提交回复
热议问题