Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I perform arithmetic operation with dates in Java? [duplicate]

Tags:

java

Possible Duplicate:
How to calculate time difference in java?

Actually I want to subtract two dates in Java. I tried a lot but can't succeed. So anyone please help me.

Date dtStartDate=pCycMan.getStartDate();

Date dtEndDate=pCycMan.getEndDate();

How can I subtract these two Dates?

like image 460
AndroidDev Avatar asked Jun 30 '11 15:06

AndroidDev


3 Answers

long msDiff = dtEndDate.getTime() - dtStartDate.getTime()

msDiff now holds the number of milliseconds difference between the two dates. Feel free to use the division and mod operators to convert to other units.

like image 177
Mike Deck Avatar answered Oct 01 '22 08:10

Mike Deck


how can i subtract these two Dates?

You can get the difference in milliseconds like this:

dtEndDate.getTime() - dtStartDate.getTime()

(getTime returns the number of milliseconds since January 1, 1970, 00:00:00 GMT.)

However, for this type of date arithmetics the Joda time library, which has proper classes for time durations (Duration) is probably a better option.

like image 41
aioobe Avatar answered Oct 01 '22 09:10

aioobe


To substract to dates you can get them both as longs getTime() and subtract the values that are returned.

like image 20
RMT Avatar answered Oct 01 '22 09:10

RMT