Overview
This article describes the various ways to format the of date and time using
DateTimeFormat
.
- Formatting Year Field
- Formatting Month Field
- Formatting Day Field
- Formatting Day Of Week Field
- Formatting Time Fields
- Using Formatting Styles: Short, Medium, Long, Full and Omit
- Define Styles Using Convenience Methods
- Custom Formatting of Date and Time Using DateTimeFormatterBuilder
Formatting Year Field
Year field can be formatter in the following three ways:
- 2 digit representation comprising of the last two digits of the year
- 4 digit representation comprising of the all the four digits of the year
- year with era information
Formatting Month Field
Month field can be formatted in the following three ways:
- Numerical representation of the month
- 3 letter representation of name of the month
- 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:
- Three letter representation
- Full representation
Formatting Time Fields
Time fields can be formatted in the following 6 ways:
- Numerical representation
- With AM/PM postfix
- Timezone short name
- Timezone full name
- Offset
- 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:
- S: Short
- M: Medium
- L: Long
- F: Full
- -: 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.