_UsingTheSimpleDateFormat

_UsingTheSimpleDateFormat

Overview

Java defines a class (java.text.SimpleDateFormat) that provides a convenient way to convert strings with date and/or time information so that it appears in your desired format.

Date and time patterns

Date and time formats are specified with date and time pattern strings. Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted with single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they are simply copied into the output string during formatting or matched against the input string during parsing.

The following pattern letters are defined (all other characters from 'A' to 'Z' and from 'a' to 'z' are reserved):

Letter

Date or time component

Examples

G

Era designator 

GG → AD 

Year 

"yy" → 14

 "yyyy" → 2014

Month in year 

"M" → 3

"MM" → 03

"MMM" → Mar

"MMMM" → March

Week in year 

"w" → 09 

Week in month 

"W" → 1

D

 Day in year

"D" → 60

"DDD" → 060

d

Day in month 

"d" →  1

"dd" → 01

Day of week in month 

"F" → 1 

Day in week 

"EEE" → Sat

 "EEEE" → Saturday

Am/pm marker 

"a" → PM

"aa" →

Hour in day (0-23) 

"H" → 8 

"HH" → 08

Hour in day (1-24) 

"k" → 8

"kk" → 08

Hour in am/pm (0-11 AM/PM) 

"K" → 8

 "KK" → 08 

Hour in am/pm (1-12, AM/PM)

"h" → 8

 "hh" → 08 

Minute in hour 

"m" → 6 

"mm" → 06

Second in minute 

"s" → 5

 "ss" → 05 

 S

Millsecond (0-999)

"SSS" → 978 

Time zone 

"z" → EST

"zz" → EST

"zzzz" → Eastern Standard Time 

Z

Time zone

-0800

Examples

For this example, consider the date and time as 2001-07-04 12:08:56 local time in the U.S. Pacific Time time zone. The following examples show how date and time patterns are interpreted in the U.S. locale:

Date and time pattern

Result

"yyyy.MM.dd G 'at' HH:mm:ss z"

2001.07.04 AD at 12:08:56 PDT

"EEE, MMM d, ''yy"

Wed, Jul 4, '01

"h:mm a"

12:08 PM

"hh 'o''clock' a, zzzz"

12 o'clock PM, Pacific Daylight Time

"K:mm a, z"

0:08 PM, PDT

"yyyyy.MMMMM.dd GGG hh:mm aaa"

02001.July.04 AD 12:08 PM

"EEE, d MMM yyyy HH:mm:ss Z"

Wed, 4 Jul 2001 12:08:56 -0700

"EEE, dd MMM yyyy HH:mm:ss z"

Wed, 04 July 2001 12:08:56 PST

You can test out a date and time pattern using this online tool.

Additional references

JavaDoc for java.text.SimpleDateFormat class