# Date math

• 04-11-2007, 01:18 AM
orchid
Date math
Am new to java and having an issue trying to do some date math.
I made this test code and it returns a date difference of 24 days which is what I wanted. My question is this the correct way to subtract dates or should I be doing something more sophisticated?
Code:

``` private void playWithDates()     {     Calendar aDay = new GregorianCalendar();     aDay.set(2007, Calendar.JANUARY, 25, 0, 0, 0);     Calendar newYearsDay = new GregorianCalendar();     newYearsDay.set(2007, Calendar.JANUARY, 1, 0, 0, 0);     long nyd=newYearsDay.getTimeInMillis();     long a=aDay.getTimeInMillis();     long diff =a-nyd;       System.out.println(diff/1000/60/60/24);     }```
output is: 24
thx
• 04-11-2007, 01:39 AM
derrickD
Well that does work so I'd say if it meets your needs then go for it.
There is a very large and involved discussion on date math that you might want to read here:
java date math
• 04-18-2007, 07:01 AM
goldhouse
Calendar class helps you to achieve this with the help roll method,
The description is as below from javadoc of sun
Code:

```roll public void roll(int field,                 int amount)     Add to field a signed amount without changing larger fields. A negative roll amount means to subtract from field without changing larger fields.     Example: Consider a GregorianCalendar originally set to August 31, 1999. Calling roll(Calendar.MONTH, 8) sets the calendar to April 30, 1999. Using a GregorianCalendar, the DAY_OF_MONTH field cannot be 31 in the month April. DAY_OF_MONTH is set to the closest possible value, 30. The YEAR field maintains the value of 1999 because it is a larger field than MONTH.     Example: Consider a GregorianCalendar originally set to Sunday June 6, 1999. Calling roll(Calendar.WEEK_OF_MONTH, -1) sets the calendar to Tuesday June 1, 1999, whereas calling add(Calendar.WEEK_OF_MONTH, -1) sets the calendar to Sunday May 30, 1999. This is because the roll rule imposes an additional constraint: The MONTH must not change when the WEEK_OF_MONTH is rolled. Taken together with add rule 1, the resultant date must be between Tuesday June 1 and Saturday June 5. According to add rule 2, the DAY_OF_WEEK, an invariant when changing the WEEK_OF_MONTH, is set to Tuesday, the closest possible value to Sunday (where Sunday is the first day of the week).     Overrides:         roll in class Calendar     Parameters:         field - the time field.         amount - the signed amount to add to field.     Since:         1.2     See Also:         add(int, int), Calendar.set(int, int)```