0

I want to calculate the duration between hours.

SimpleDateFormat defaultFormat = new SimpleDateFormat("HH:mm");
Date hour1 = defaultFormat.parse(time1);
Date hour2 = defaultFormat.parse(time2);
duration = (time2.getTime() - time1.getTime()) / (1000*60); //to minutes
/* hours= duration/60 (hours)  minutes = duration%60 (minutes)

Especially the problem occurs when for example hour1 is "22:15" and hour2 is "01:15". The above piece of code save to "duration = 1260" (21 hours).

How can i find the difference between two hours without any bugs?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

4 Answers4

0

Mind that you might hit a daylight saving timezone shift date and then difference between 23:00 and 3:00 may be 4, 3 or 5 hours. I'd suggest you using JodaTime Duration and Period classes in Java 7 or the similar API in Java 8

Piotr Gwiazda
  • 12,080
  • 13
  • 60
  • 91
0

I suggest you to use Joda-Time when it comes to manipulate dates and times in Android, or any other Java app. It is much more powerful than the native Java date class.

Here is an example using Joda-Time:

DateTime startTime;
DateTime endTime;
Period p = new Period(startTime, endTime);
int hours = p.getHours();
int minutes = p.getMinutes();
DustyMan
  • 366
  • 3
  • 9
  • 1
    FYI, the [Joda-Time](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to the [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes built into Java 8 and later. Much of the java.time functionality is back-ported to Java 6 & 7 in [ThreeTen-Backport](http://www.threeten.org/threetenbp/) and further adapted to Android in [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP). – Basil Bourque Feb 01 '17 at 23:13
0

Feature, not a bug.

You are inappropriately using a date-time class to represent a time-of-day value. Also, you are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.

Use LocalTime class for a time-of-day only value, without a date and without a time zone or offset.

LocalTime lt = LocalTime.of( "22:15" ) ;

You can do math using the Duration class.

Duration d = Duration.of( startLocalTime , stopLocalTime );

The catch with using a time-of-day-only value is wrapping around the clock, crossing over midnight. Without the context of dates, how could you expect a proper result? Going from "22:15" to "01:15" did you mean to roll into the next day, the next week, or the next year?

The Duration class takes the approach of not crossing midnight. The range of values for LocalTime is a total of twenty-four hours, running from the minimum of 00:00 to the maximum of 23:59:59.999999999. So the only way to go from a later time to an earlier time is to travel backwards in time to the earlier point, resulting in a negative number.

LocalTime start = LocalTime.parse ( "22:15" );
LocalTime stop = LocalTime.parse ( "01:15" );
Duration d = Duration.between ( start , stop );

Dump to console.

System.out.println ( "start/stop: " + start + "/" + stop );
System.out.println ( "d.toString(): " + d );

start/stop: 22:15/01:15

d.toString(): PT-21H

That output is standard ISO 8601 format for durations.

If you want to calculate spans of time between actual moments on the timeline, search for Stack Overflow for java.time, Duration, Period, ZonedDateTime, ZoneId, OffsetDateTime, Instant, Interval, and “elapsed”. This topic has been covered many times already.

As a quick example, let’s assign some arbitrary dates running from January 23rd to 24th of this year in the zone of America/Montreal. Result is three hours of elapsed time. This result might vary by date and zone because of anomalies such as Daylight Saving Time (DST).

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdtStart = ZonedDateTime.of( 2017, 1, 23, 22, 15, 0, 0 , z );
ZonedDateTime zdtStop = ZonedDateTime.of( 2017, 1, 24, 01, 15, 0, 0 , z );
Duration d = Duration.between( zdtStart , zdtStop );

zdtStart.toString(): 2017-01-23T22:15-05:00[America/Montreal]

zdtStop.toString(): 2017-01-24T01:15-05:00[America/Montreal]

d.toString(): PT3H

See that code run live at IdeOne.com.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

java.time

You can use java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenience methods were introduced.

Demo:

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class Main {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalTime startTime = LocalTime.parse("22:15");
        LocalTime endTime = LocalTime.parse("01:15");

        LocalDateTime startDateTime = today.atTime(startTime);
        LocalDateTime endDateTime = today.atTime(endTime);

        if (startDateTime.isAfter(endDateTime)) {
            endDateTime = endDateTime.with(LocalTime.MIN).plusDays(1).with(endTime);
        }

        Duration duration = Duration.between(startDateTime, endDateTime);
        // Default format
        System.out.println(duration);

        // Custom format
        // ####################################Java-8####################################
        String formattedDuration = String.format("%02d:%02d:%02d", duration.toHours(), duration.toMinutes() % 60,
                duration.toSeconds() % 60);
        System.out.println(formattedDuration);
        // ##############################################################################

        // ####################################Java-9####################################
        formattedDuration = String.format("%02d:%02d:%02d", duration.toHoursPart(), duration.toMinutesPart(),
                duration.toSecondsPart());
        System.out.println(formattedDuration);
        // ##############################################################################
    }
}

Output:

PT3H
03:00:00
03:00:00

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

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110