The most frequently used concept in Joda-Time is that of the instant. An Instant is defined as an instant in the datetime continuum specified as a number of milliseconds from 1970-01-01T00:00Z. This definition of milliseconds is consistent with that of the JDK in Date or Calendar. Interoperating between the two APIs is thus simple.
The millisecond instant can be converted to any date time field using a Chronology. To assist with this, methods are provided on DateTime that act as getters for the most common date and time fields. More powerful access to the field can be obtained via its property.
DateTime dt = new DateTime(); // current time int month = dt.getMonth(); // gets the current month int month = dt.month().get(); // alternative way to get value String monthStr = dt.month().getAsText(); // gets the month name
To deal with local times (no time zone), or with date only or time only concepts, you should use the partial classes.
Within Joda-Time an instant is represented by the ReadableInstant interface. There are four implementations of the interface provided:
The code can be used in various ways:
// setup date object for midday on Christmas 2004 (ISO year 2004) DateTime dt = new DateTime(2004, 12, 25, 12, 0, 0, 0); // get the year, 2004 int year = dt.getYear(); // get the day of week index 1 (Monday) to 7 (Sunday) int dow = dt.getDayOfWeek(); // get the text, such as 'Tuesday' String dowStr = dt.dayOfWeek().getAsText();
// construct DateTime from JDK Date Date jdkDate = new Date(); DateTime dt = new DateTime(jdkDate); // construct Calendar from DateTime (could also construct a Date) GregorianCalendar cal = dt.toGregorianCalendar();
Note that the interface ReadableInstant should not be used like the collections API. The interface only contains the core subset of the operations of DateTime. You should use the interface only when you feel the need to be flexible about future changes to the object passed into a method. You might also want to consider the ReadableDateTime interface which extends ReadableInstant to provide additional methods.