What are some good ways to customize date/time display format for different localization

Cheok Yan Cheng :

Whenever I want to print out date/time format to a human readable form, IDE will recommend me to use one of the following way

getDateInstance()
getDateTimeInstance()
getTimeInstance()

However, most of the time, applying different int style doesn't meet my requirement. End up, I need to define my own.

private static final ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = new ThreadLocal <SimpleDateFormat>() {
    @Override protected SimpleDateFormat initialValue() {
        // January 2
        return new SimpleDateFormat("MMMM d");
    }
};

This create a trouble for me, if I want to support non-English as well. For instance, for Chinese market, I need to use separate format.

private static final ThreadLocal<SimpleDateFormat> dateFormatForChineseThreadLocal = new ThreadLocal <SimpleDateFormat>() {
    @Override protected SimpleDateFormat initialValue() {
        // 1月2日
        return new SimpleDateFormat("MMMMd日");
    }
};

My code will end up with the following

public String dateString() {
    if (chinese user) {
        return dateFormatForChineseThreadLocal.get().format(calendar.getTime());
    }
    return dateFormatThreadLocal.get().format(calendar.getTime());
}

This make maintenance job difficult. I was wondering, is there a better way, to customize date/time display format for different localization?

Denis Loh :

When you localize your app you usually create strings.xml files for each language your app shall support in /src/main/res/, where values/ contains mostly english files and in values-de or values-cn german or chinese for instance. When you define a string resource with your format there, you can simply read that out and pass that format to your date formatter.

With this, you can simply add new languages without changing any line in your code.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=108489&siteId=1