How to perform arithmetic operation with dates in Java?

Possible duplicate:
How to calculate time difference in java?

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

Date dtStartDate=pCycMan.getStartDate(); Date dtEndDate=pCycMan.getEndDate(); 

How can I subtract these two terms?

+4
source share
8 answers
 long msDiff = dtEndDate.getTime() - dtStartDate.getTime() 

msDiff now contains the number of millisecond differences between two dates. Feel free to use the division operators and mod to convert to other units.

+5
source

How can I subtract these two dates?

You can get the difference in milliseconds as follows:

 dtEndDate.getTime() - dtStartDate.getTime() 

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

However, for this type of date arithmetic, the Joda time library , which has the appropriate classes for Duration , is probably the best option.

+4
source

To subtract dates, you can get them as longs getTime() and subtract the return values.

+1
source

Use the Calendar class.

Using:

 Calendar c = Calendar.getInstance(); c.setTime(dtStartDate); int date = c.get(Calendar.YEAR); //int represents the year of the date int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); // int represents dayOfWeek as defined in link. 
0
source

Create two Calendar objects from these dates, and then use the add () method (which you can also use to fake the date).

0
source

There is a framework for working with dates in java ... http://joda-time.sourceforge.net/userguide.html take a look, I'm sure it can help you.

0
source
 long diffInMillis = dtEndDate.getTimeInMillis() - dtStartDate.getTimeInMillis(); 
0
source

It depends on what you want. To get the difference in milliseconds, say dtStartDate.getTime() - dtEndDate.getTime() .

To get the difference in days, hours, etc., use the calendar class (methods like after, before, compareTo, roll can help).

0
source

All Articles