Android Java : How to subtract two times?

后端 未结 5 1091
滥情空心
滥情空心 2020-12-15 08:56

I use some kind of stopwatch in my project and I have

start time ex: 18:40:10 h
stop time  ex: 19:05:15 h

I need a result from those two

5条回答
  •  难免孤独
    2020-12-15 09:36

    I am providing the modern answer.

    java.time and ThreeTenABP

        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("H:mm:ss 'h'");
    
        String startTimeString = "18:40:10 h";
        String stopTimeString = "19:05:15 h";
    
        LocalTime startTime = LocalTime.parse(startTimeString, timeFormatter);
        LocalTime stopTime = LocalTime.parse(stopTimeString, timeFormatter);
    
        if (stopTime.isBefore(startTime)) {
            System.out.println("Stop time must not be before start time");
        } else {
            Duration difference = Duration.between(startTime, stopTime);
    
            long hours = difference.toHours();
            difference = difference.minusHours(hours);
            long minutes = difference.toMinutes();
            difference = difference.minusMinutes(minutes);
            long seconds = difference.getSeconds();
    
            System.out.format("%d hours %d minutes %d seconds%n", hours, minutes, seconds);
        }
    

    Output from this example is:

    0 hours 25 minutes 5 seconds

    The other answers were good answers in 2010. Today avoid the classes DateFormat, SimpleDateFormat and Date. java.time, the modern Java date and time API, is so much nicer to work with.

    But doesn’t it require API level 26?

    No, using 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) 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.

提交回复
热议问题