Search code examples
javadatetimesubtraction

Java returns wrong Time object when comparing two Times


I was creating a masterpiece today in java and I needed to calcualte the difference between two times.

So I used Time.getTime() to get long values of the times and subtracted them to get what I want ...

This is my test code :

public static void main(String[] args) {    
    Time time = new Time(00,00,00);
    Time time2 = new Time(02,00,00);
    long longTime = (time2.getTime() - time.getTime());
    Time finalTime = new Time(longTime);
    System.out.println(finalTime.toString());
}

Now Apparently the printed out string must be 02:00:00

But I am always getting 04:00:00

I tried to change the times a lot , I am always getting the time increased by two hours and I couldn't know why.

I even tried to subtract 00:00:00 and 00:00:00

and instead of getting 00:00:00

I got 02:00:00

So , any help for me ???


Solution

  • Here is the deal ...

    First of all if it is possible , I suggest to not use the class Time as its methods are mostly deprecated.

    Instead try to use Date class or Duration and Instant https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html

    If you have to stick with this class for now , here is the trick.

    The constructor new Time(long) takes the timezone offset in consideration ...

    So if you are at +02 timezone ... your time object will be increased in 120 minutes.

    To solve this you can use Time.getTimezoneOffset()

    This method will return an integer with the number of minutes from your timezone

    I edited my code to this and now it is working properly:

    public static void main(String[] args) {
    
    
        Time time = new Time(00,00,00);
        Time time2 = new Time(02,00,00);
    
        long longTime = (time2.getTime() - time.getTime());
    
        Time finalTime = new Time(longTime);
    
        int timeOffset = time.getTimezoneOffset();
        finalTime.setMinutes(finalTime.getMinutes()+timeOffset);
    
        System.out.println(finalTime.toString());   
    
        }