JodaTime DateTimeFormat

Overview

This article describes the various ways to format the of date and time using
DateTimeFormat
.

  1. Formatting Year Field
  2. Formatting Month Field
  3. Formatting Day Field
  4. Formatting Day Of Week Field
  5. Formatting Time Fields
  6. Using Formatting Styles: Short, Medium, Long, Full and Omit
  7. Define Styles Using Convenience Methods
  8. Custom Formatting of Date and Time Using DateTimeFormatterBuilder

Formatting Year Field

Year field can be formatter in the following three ways:

  1. 2 digit representation comprising of the last two digits of the year
  2. 4 digit representation comprising of the all the four digits of the year
  3. year with era information


Formatting Month Field

Month field can be formatted in the following three ways:

  1. Numerical representation of the month
  2. 3 letter representation of name of the month
  3. Full representation of name of the month


Formatting Day Field


Formatting Day Of Week Field

Day of Week field can be formatted in two ways:

  1. Three letter representation
  2. Full representation


Formatting Time Fields

Time fields can be formatted in the following 6 ways:

  1. Numerical representation
  2. With AM/PM postfix
  3. Timezone short name
  4. Timezone full name
  5. Offset
  6. Offset full description


Using Formatting Styles: Short, Medium, Long, Full and Omit

Joda-Time provides the following predefined styles for formatting date and time fields:

  1. S: Short
  2. M: Medium
  3. L: Long
  4. F: Full
  5. -: Omit Style (i.e. Omit applying any formatting style)

DateTimeFormat.forStyle()
method takes in two characters (the first for date and second for time) from the above styles to be applied for DateTime formatting.


Define Styles Using Convenience Methods

In the
previous example
, we discussed how to define styles using ‘two character’ notation convention.

In this example, we shall see how to use the convenience method in
DateTimeFormat
class to define styles: The convenience methods defined in
DateTimeFormat
are:

  • Date Related: DateTimeFormat.fullDate(), DateTimeFormat.longDate(), DateTimeFormat.mediumDate() and DateTimeFormat.shortDate()
  • Time Related: DateTimeFormat.fullTime(), DateTimeFormat.longTime(), DateTimeFormat.mediumTime() and DateTimeFormat.shortTime()


Custom Formatting of Date and Time Using DateTimeFormatterBuilder

Joda-Time provides a feature to define custom representations of DateTime formats.

This is possible using the
DateTimeFormatterBuilder
class as shown below.

In the following example, the DateTime is formatted for the following custom format:

Wednesday, the 15th day of October in year 2014 at 7 hours, 30 minutes and 45 seconds


To start, click on the next arrow. If you find anything missing in the tutorials then please drop in your comments.

Leave a Comment