Introduction
In this post we saw how to format dates according to some ISO and RCF standards. They can help you to quickly format a date in a standardised way. However, if you’re looking for date localisation then you’ll need something else.
By localising dates we mean that we want to show dates in an application according to the user’s region. A Japanese user will want to see the dates according to the Japanese date convention. You can store UTC dates internally according to an ISO standard but follow some local convention when presenting it on the screen.
Locales
A Locale represents a region and one or more corresponding cultures, most often with a country and one or more languages. You can easily list all available Locales:
Locale[] locales = Locale.getAvailableLocales();
for (Locale locale : locales)
{
System.out.println(locale.getCountry());
System.out.println(locale.getDisplayCountry());
System.out.println(locale.getDisplayLanguage());
}
You’ll see values such as…
PE
Peru
Spanish
ID
Indonesia
Indonesian
GB
United Kingdom
English
Some locales are stored as static properties of the Locale object, e.g.:
Locale.JAPAN
Locale.FRANCE
Locale.US
We’ll need to use the ZonedDateTime object to format a date according to a Locale. The following code will format the UTC date according to the US standard:
ZonedDateTime utcDateZoned = ZonedDateTime.now(ZoneId.of("Etc/UTC"));
DateTimeFormatter pattern = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.US);
System.out.println(utcDateZoned.format(pattern));
The output will be Friday, November 21, 2014 1:45:14 PM UTC.
Let’s see the UTC dates in France and Japan:
DateTimeFormatter pattern = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE);
System.out.println(utcDateZoned.format(pattern));
… vendredi 21 novembre 2014 13 h 50 UTC
DateTimeFormatter pattern = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.JAPAN);
System.out.println(utcDateZoned.format(pattern));
2014年11月21日 13時51分34秒 UTC
View all posts related to Java here.
Like this:
Like Loading...