Java Reference
In-Depth Information
Formatting date: 2012-04-30
M/d/yyyy: 4/30/2012
MM/dd/yyyy: 04/30/2012
MMM dd, yyyy: Apr 30, 2012
MMMM dd, yyyy: April 30, 2012
EEEE, MMMM dd, yyyy: Monday, April 30, 2012
'Month' q 'in' QQQ: Month 2 in Q2
[MM-dd-yyyy][' at' HH:mm:ss]: 04-30-2012
Formatting time:16:30:05.000078899
HH:mm:ss: 16:30:05
KK:mm:ss a: 04:30:05 PM
[MM-dd-yyyy][' at' HH:mm:ss]: at 16:30:05
Formatting zoned datetime:2012-04-30T16:30:05.000078899-05:00[America/Chicago]
MM/dd/yyyy HH:mm:ssXXX: 04/30/2012 16:30:05-05:00
MM/dd/yyyy VV: 04/30/2012 America/Chicago
[MM-dd-yyyy][' at' HH:mm:ss]: 04-30-2012 at 16:30:05
Using Locale Specific Formats
The
DateTimeFormatter
class has several methods that return a
DateTimeFormatter
with a predefined formatting
pattern suitable for humans to read. Use the following methods to obtain a reference to such formatters:
DateTimeFormatter ofLocalizedDate(FormatStyle dateStyle)
•
DateTimeFormatter ofLocalizedDateTime(FormatStyle dateTimeStyle)
•
DateTimeFormatter ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle
timeStyle)
•
DateTimeFormatter ofLocalizedTime(FormatStyle timeStyle)
These methods accept an argument of
FormatStyle
enum type, which has four constants:
SHORT
,
MEDIUM
,
LONG
,
and
FULL
. These constants are used to output formatted date and time with a varying degree of detail. The details in
the output are locale-specific. The methods use the system default locale. For a different locale, use the
withLocal()
method to obtain a new
DateTimeFormatter
with the specified locale.
Listing 12-25 shows how to use some predefined locale-specific formats. It formats dates and times in US
(default), German, and Indian locales.
•
Listing 12-25.
Using Predefined Format Patterns
// LocalizedFormats.java
package com.jdojo.datetime;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import static java.time.format.FormatStyle.FULL;