5

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?

Community
  • 1
  • 1
AndroidDev
  • 4,521
  • 24
  • 78
  • 126

8 Answers8

6

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.

aioobe
  • 413,195
  • 112
  • 811
  • 826
6
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.

Mike Deck
  • 18,045
  • 16
  • 68
  • 92
  • As others have noted, for anything more complex than this, Joda Time is definitely the way to go. – Mike Deck Jun 30 '11 at 15:19
  • but i want the result like 20-jun-2011 - 1-june-2011=28 – AndroidDev Jun 30 '11 at 15:31
  • @Anshuman, I have no idea how June 20th minus June 1st would equal 28. What units are you looking for? Seems to me it would equal 19 days. To get the number of days just use the code in my answer and then do `msDiff / (1000 * 60 * 60 * 24)`. – Mike Deck Jun 30 '11 at 16:56
  • hi Mike i have done it like this but it will give me the result in negative long lDiffFromToday = currentDate.getTime()-dtSelDate.getTime();lDiffFromToday=lDiffFromToday/(1000 * 60 * 60 * 24); – AndroidDev Jul 01 '11 at 05:47
1

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

RMT
  • 7,040
  • 4
  • 25
  • 37
0

Use the Calendar class.

Usage:

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.
nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
0

Create two Calendar objects from those Dates and then use the add() method (which can be used to subtrade dates too).

marchaos
  • 3,316
  • 4
  • 26
  • 35
0

There is a framework to work with the date in java... http://joda-time.sourceforge.net/userguide.html take a look, i'm sure that it can help you

rascio
  • 8,968
  • 19
  • 68
  • 108
0
long diffInMillis = dtEndDate.getTimeInMillis() -  dtStartDate.getTimeInMillis();
Bala R
  • 107,317
  • 23
  • 199
  • 210
0

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

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

AlexR
  • 114,158
  • 16
  • 130
  • 208