# Working with legacy Date/Calendar types

version 2.5.1

The `groovy-dateutil` module supports numerous extensions for working with Java’s classic `Date` and `Calendar` classes.

You can access the properties of a `Date` or `Calendar` using the normal array index notation with the constant field numbers from the `Calendar` class as shown in the following example:

    import static java.util.Calendar.*    (1)

    def cal = Calendar.instance
    cal[YEAR] = 2000                      (2)
    cal[MONTH] = JANUARY                  (2)
    cal[DAY_OF_MONTH] = 1                 (2)
    assert cal[DAY_OF_WEEK] == SATURDAY   (3)

1 | Import the constants
2 | Setting the calendar’s year, month and day of month
3 | Accessing the calendar’s day of week

Groovy supports arithmetic on and iteration between `Date` and `Calendar` instances as shown in the following example:

    def utc = TimeZone.getTimeZone('UTC')
    Date date = Date.parse("yyyy-MM-dd HH:mm", "2010-05-23 09:01", utc)

    def prev = date - 1
    def next = date + 1

    def diffInDays = next - prev
    assert diffInDays == 2

    int count = 0
    prev.upto(next) { count++ }
    assert count == 3

You can parse strings into dates and output dates into formatted strings:

    def orig = '2000-01-01'
    def newYear = Date.parse('yyyy-MM-dd', orig)
    assert newYear[DAY_OF_WEEK] == SATURDAY
    assert newYear.format('yyyy-MM-dd') == orig
    assert newYear.format('dd/MM/yyyy') == '01/01/2000'

You can also create a new Date or Calendar based on an existing one:

    def newYear = Date.parse('yyyy-MM-dd', '2000-01-01')
    def newYearsEve = newYear.copyWith(
        year: 1999,
        month: DECEMBER,
        dayOfMonth: 31
    )
    assert newYearsEve[DAY_OF_WEEK] == FRIDAY