Substracting Date in java return bad result

Advertisements

Hi I’ve tried to substract hour from a Date using Date.getTime() – (time in ms ) but the result is not correct , there is always a slight gap compared to the good result, any idea ?

if(hoursToBeSubstracted<1) { 
            float toMinute = hoursToBeSubstracted*60;
            return new Date((long)(d1.getTime()-toMinute*60000));
        }
        return new Date((long)(d1.getTime() - 3600 * hoursToBeSubstracted * 1000));

Example of output :

Before operation Thu Dec 01 13:27:30 CET 2022
Substracting 60.0 minutes
After operation Thu Dec 01 12:28:31 CET 2022
Before operation Wed Nov 30 16:48:52 CET 2022
Substracting 60.0 minutes
After operation Wed Nov 30 15:49:53 CET 2022
Before operation Wed Nov 30 16:48:52 CET 2022
Substracting 60.0 minutes
After operation Wed Nov 30 15:49:53 CET 2022
Before operation Wed Nov 30 16:48:52 CET 2022
Substracting 60.0 minutes
After operation Wed Nov 30 15:49:53 CET 2022
Before operation Thu Dec 01 13:27:30 CET 2022
Substracting 60.0 minutes
After operation Thu Dec 01 12:28:31 CET 2022

>Solution :

java.time

The java.time API, released with Java-8 in March 2014, supplanted the error-prone legacy date-time API. Since then, it has been strongly recommended to use this modern date-time API.

Solution using modern date-time API

Convert your java.util.Date instance to java.time.Instant and subtract hours using Instant#minus.

Demo:

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        Date date = new Date(); // A sample java.util.Date
        Instant instant = date.toInstant();
        Instant updated = instant.minus(3, ChronoUnit.HOURS); // Subtracting 3 hours
        System.out.println(updated);
    }
}

Output:

2022-12-02T07:13:10.426Z

For any reason, if you want to get java.util.Date again, you can do so by using Date#from.

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

One thought on “Substracting Date in java return bad result

Leave a ReplyCancel reply