04/07/2012

[Java] Format date with locale

In Java, you may need to format a date using a particular pattern or locale. You can easily do it with SimpleDateFormat:

SimpleDateFormat sdf = new SimpleDateFormat(pattern, locale);
Date date = Calendar.getInstance().getTime();
sdf.format(date); 

This code formats the current date using the given pattern and locale.



Patterns are well defined in the SimpleDateFormat class specification linked above and should be something like:

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
"yyMMddHHmmssZ" 010704120856-0700

While locale should be something like: "Locale.Italian"

No comments:

Post a Comment

With great power comes great responsibility