Question

My time difference is showing an incorrect output, I'm trying to calculate the time difference between startTime and endTime.

    Date time1, time2;
    long difference;

    SimpleDateFormat df = new SimpleDateFormat("HH:mm");

    public Time(String startTime, String endTime)
    {
        this.startTime = startTime;
        this.endTime = endTime;

        time1 = new Time("16:30", "18:00"); //example

        try
        {
            time1 = df.parse(startTime);
            time2 = df.parse(endTime);
        }
        catch(Exception e) {
           System.out.println("invalid time");
        }
    }

    public String getDifference()
    {
         difference = (time2.getTime() - time1.getTime());
         return df.format(difference); //output = 02:30, should be 01:30
    }

I know that Joda-Time could make this easier, but I'm supposed not to use any other library.

Was it helpful?

Solution 2

Time is the number of milliseconds since a moment called epoch. In your code, you calculate the difference between to moments, and then interpret the result as a timestamp, but it isn't.

The calculated result is the difference between two timestamps in milliseconds. If you want that printed in hours and minutes, do something like:

public String getDifference() {
    difference = (time2.getTime() - time1.getTime()) / 1000L;
    long hours = difference/3600;
    difference %= 3600;
    long minutes = difference/60;
    difference %= 60;
    long seconds = difference;

    return String.format("%d:%02d:%02d", hours, minutes, seconds);
}

OTHER TIPS

It calculates the difference correctly as 5400000 milliseconds (1.5 hours), but formats it as 02:30, due to, I think, the time zone.

Add this line in your constructor to set the date format to the UTC time zone, and it should output 01:30 as you expect:

df.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));

The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.

Demo:

import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:m", Locale.ENGLISH);
        LocalTime begin = LocalTime.parse("16:30", dtf);
        LocalTime end = LocalTime.parse("18:00", dtf);
        Duration duration = Duration.between(begin, end);
        System.out.println(duration);

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

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

Output:

PT1H30M
1:30
1:30

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top