Using Joda-Time

Introduction

Joda-Time is a library to overcome some of the limitations of Java's built-in Date and Calendar classes. Some of the key classes include:

Class Description
DateTime Immutable replacement for JDK Calendar
DateMidnight Immutable class representing a date where the time is forced to midnight
LocalDate Immutable class representing a local date without a time (no time zone)
LocalTime Immutable class representing a time without a date (no time zone)
LocalDateTime Immutable class representing a local date and time (no time zone)

Make sure you add the joda-time-x.x.x jar to your classpath before running these examples. We used version 1.5.2.

Creating instances

Frequently you will use the DateTime class as follows:

import org.joda.time.DateTime
def today = new DateTime()
println today
int month = today.monthOfYear
println month

which will produce output like this:

2008-09-27T14:16:16.067+10:00
9

You can access fields of a DateTime instant using numerous properties:

println today.era
println today.year
println today.weekyear
println today.yearOfEra
println today.yearOfCentury
println today.monthOfYear
println today.weekOfWeekyear
println today.dayOfYear
println today.dayOfMonth
println today.dayOfWeek

which will produce output like this:

1
2008
2008
2008
8
9
39
271
27
6

Times Periods

You can also use time periods:

import static org.joda.time.Period.*
def lastNewYears = new DateTime(2008, 1, 1, 12, 0, 0, 0)
println lastNewYears
def isLeap = lastNewYears.year().isLeap()
def nextNewYears = lastNewYears + days(isLeap ? 366 : 365)
println nextNewYears

which will produce output like this:

2008-01-01T12:00:00.000+10:00
2009-01-01T12:00:00.000+10:00

Input and Output

You can also input or output dates and times using various formatting helper classes including a powerful format building class or using Groovy's GStrings:

import org.joda.time.format.*
def input = "20080125"
def fmt_in = DateTimeFormat.forPattern("yyyyMMdd")
def fmt_out = ISODateTimeFormat.dateTime()
println fmt_out.print(fmt_in.parseDateTime(input))

def fmt = new DateTimeFormatterBuilder().
    appendDayOfMonth(2).
    appendLiteral('-').
    appendMonthOfYearShortText().
    appendLiteral('-').
    appendTwoDigitYear(1956).  // pivot year
    toFormatter()
println fmt.print(today)

println "$today.dayOfMonth-${today.monthOfYear.toString().padLeft(2, '0')}-$today.year"

which will produce output like this:

2008-01-25T00:00:00.000+10:00
27-Sep-08
27-09-2008

Further Information

Copyright (c) 2008 Paul King. All rights reserved.