EXP0
EXP0

Reputation: 882

How to add the difference of two Dates to the third Date in Java?

I'm new to Java, and I did some search in google and this forum, but I'm still not sure what is a good way to do this. (Joda time is not an option to me).

Date d1;
Date d2;
Date d3;
float a;

what is a good way for me to do:

d3 + a - (d1 - d2);

Do I need to get the millisecond between d1 and d2, and then convert d3 to calendar to add the millisecond to it?

Thank you!

Edit: I should have mentioned that float a represents number of minutes, e.g. a = 35.6 minutes.

Upvotes: 0

Views: 334

Answers (1)

Bohemian
Bohemian

Reputation: 424983

It depends on what you mean by "difference" - difference can have a direction or be absolute.

If you want to add the absolute gap, use this:

Date result = new Date(d3.getTime() + Math.abs(d2.getTime() - d1.getTime()));

If you care about d2 being relative to d1 (ie if d2 is before d1 you actually subtract the gap), then use:

Date result = new Date(d3.getTime() + d2.getTime() - d1.getTime());

EDITED:

In response to comments, yes: If float a is a number of minutes, you can further add a * 60000 to get a new long number of milliseconds and create a new Date from that.

Upvotes: 4

Related Questions