Monday, May 3, 2010

Sample DateTimeFormatter with locale

Do not change locale system wide , do not disturb others!
Create different locales and formatters with given locale and use them.

import java.text.*;
import java.util.*;

public class DateTimeFormatter {

private static final Locale ukrainianLocale = new Locale ("uk", "UA");
private static final Locale russianLocale = new Locale ("ru", "RU");
private static final Locale englishLocale = new Locale ("en", "EN");

public static DateFormat ukranianDateFormatter;
public static DateFormat russianDateFormatter;
public static DateFormat englishDateFormatter;

public DateTimeFormatter (String dateFormatPattern) {
ukranianDateFormatter = new SimpleDateFormat (dateFormatPattern, ukrainianLocale);
russianDateFormatter = new SimpleDateFormat (dateFormatPattern, russianLocale);
englishDateFormatter = new SimpleDateFormat (dateFormatPattern, englishLocale);

public static String format (Date date, String lang) {
String formattedDateTime;
if ("ru".equalsIgnoreCase (lang)) {
formattedDateTime = russianDateFormatter.format (date);
} else if ("en".equalsIgnoreCase (lang)) {
formattedDateTime = englishDateFormatter.format (date);
} else {
formattedDateTime = ukranianDateFormatter.format (date);
return formattedDateTime;

public static void main (String[] args) {
DateTimeFormatter df = new DateTimeFormatter ("dd/MMM/yy HH:mm");
Date now = new Date ();
System.out.println ("uk date:" + df.format (now, "uk"));
System.out.println ("en date:" + df.format (now, "EN"));
System.out.println ("ru date:" + df.format (now, "ru"));

uk date:03/трав/10 16:17
en date:03/May/10 16:17
ru date:03/май/10 16:17

No comments:

Post a Comment