views:

24

answers:

2

Hi,

I'm trying to get the difference between 2 dates in days, hours, and seconds:

import groovy.time.*

Date now = new Date()

// Using deprecated constructor just for this example
Date newYearsDay2000 = new Date(2000, 0, 1)

use (TimeCategory) {
    now - newYearsDay2000
}

This prints:

-690023 days, -14 hours, -38 minutes, -27.182 seconds

Which is obviously nothing like the difference between today's date and 2000/1/1, where am I going wrong?

Thanks, Don

+3  A: 

Could be an issue with the deprecated constructor?

If you use Calendar (and the Groovy updated method) to create the newYearsDay2000 var, you get:

import groovy.time.*
import static java.util.Calendar.*

Date now = new Date()
// Use the static imported Calendar class
Date newYearsDay2000 = instance.updated( year:2000, month:JANUARY, day:1 ).time

use( TimeCategory ) {
    now - newYearsDay2000
}

which gives the result:

3925 days, 23 hours, 59 minutes, 59.999 seconds

Edit

Yeah, the JavaDoc for Date shows that constructor with the comment:

Date(int year, int month, int date)

Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).

Which leads me to believe that:

Date newYearsDay2000 = new Date(2000, 0, 1)

Is actualy creating the Date for new Years Day in the year 3900

tim_yates
Very well spotted, take a bow!
Don
A: 

Date Parameters: year - the year minus 1900.

Frayser