0

Possible Duplicate:
How do you subtract Dates in Java?

I am creating java desktop application. In that application user give some date inputs. so i use 3party library "jCalendar.jar". for validation i want to subtract two dates. is there any way to subtract two dates in java?

Community
  • 1
  • 1
Siddhu
  • 107
  • 1
  • 8

4 Answers4

4

Java doesn't give toomuch, you can look at open source: try JODA.

DateTime dt1 = new DateTime(2000, 1, 1, 0, 0, 0, 0);
DateTime dt2 = new DateTime(2010, 1, 1, 0, 0, 0, 0);
int noOfdays = Days.daysBetween(dt1, dt2).getDays();
amicngh
  • 7,831
  • 3
  • 35
  • 54
2

I would recommend taking a look at Joda Time, the de-facto standard for date handling in Java. Given two java.util.Dates, javaDate1, and javaDate2:

DateTime d1 = new DateTime(javaDate1);
DateTime d2 = new DateTime(javaDate2);

Period diff = new Period(d1, d2);

You can now query the diff object for the difference, split into it's constituent components (years, months, days, etc.). See the Joda Time period guide for more info.

Barry Wark
  • 107,306
  • 24
  • 181
  • 206
2

If you are using a Java Date or Java Calendar, then you could use something like:

Calendar firstOperand = new GregorianCalendar();
Calendar secondOperand = new GregorianCalendar();
Calendar result = new GregorianCalendar();

result.setTimeInMillis(firstOperand.getTimeInMillis() - secondOperand.getTimeInMillis());

edit: As pointed in the comments, storing the result in a calendar wouldn't make much sense. You can still use the milliseconds returned for your operations.

If possible you could also use a library to handle this, like JODA.

It allows you to get the number of seconds/minutes/days/months/etc from between two dates and more things.

Josejulio
  • 1,286
  • 1
  • 16
  • 30
  • This is a bit strange. Suppose I subtract 5 August 2012, 12:34 from 13 August 2012, 15:41 and put the result in a `Calendar`. What date would you expect the `Calendar` to be set on? The result of subtracting two dates is an amount of time, not a moment in time. `Calendar` is not suited to holding an amount of time. – Jesper Aug 15 '12 at 09:51
  • You are right, on second though is a bit strange, but is what i though on that moment, still he can use the milliseconds on a different way instead of setting on the Calendar. – Josejulio Aug 15 '12 at 15:34
  • This helps my work. Thanks! – Tung Oct 14 '16 at 16:35
0

You can use java.util.GregorianCalendar

Create an instance of this class then call the setTime() method to set your date. Finally use the methods of this class.

Valerio Emanuele
  • 909
  • 13
  • 27