Maxime Painchaud Maxime Painchaud - 2 months ago 9
Java Question

Add a Double variable representing minute into a Date in Java

I have a Origin-Destination matrix representing the distance between 2 point in minute. I wonder what is the best way to add the distance to a Date.

Date clock;
SimpleDateFormat reqDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
clock = reqDF.parse(line[25]);
Double distance = distDB.find_distance(O, D, mode, facility_id);
Date current_time = clock + distance;


Does it makes more easier if I use a Calendar type instead of Date ?

Thanks

Answer

You could try this:

Date clock;
SimpleDateFormat reqDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
clock = reqDF.parse(line[25]);
Double distance = distDB.find_distance(O, D, mode, facility_id);

long clockTimeMs = clock.getTime();
long distTimeInMs = Math.round(distance * 60000);
Date current_time = new Date(clockTimeMs + distTimeInMs);

Here the Date gets converted into a milliseconds timestamp. Since the distance is in minutes, you need to convert it also into milliseconds by multiplying it by 60 * 1000 (= 60000) before you can add it to the start time ("clock"). Finally a new Date gets created that represents the distance from the start time.

Please find details of the Date class here: https://docs.oracle.com/javase/6/docs/api/java/util/Date.html