How do I get localized date pattern string?

前端 未结 10 2271
死守一世寂寞
死守一世寂寞 2020-11-28 05:31

It is quite easy to format and parse Java Date (or Calendar) classes using instance of DateFormat, i.e. I could format current date into short localize date like this:

10条回答
  •  無奈伤痛
    2020-11-28 06:14

    Please find in the below code which accepts the locale instance and returns the locale specific data format/pattern.

     public static String getLocaleDatePattern(Locale locale) {
        // Validating if Locale instance is null
        if (locale == null || locale.getLanguage() == null) {
            return "MM/dd/yyyy";
        }
        // Fetching the locale specific date pattern
        String localeDatePattern = ((SimpleDateFormat) DateFormat.getDateInstance(
                DateFormat.SHORT, locale)).toPattern();
        // Validating if locale type is having language code for Chinese and country 
        // code for (Hong Kong) with Date Format as - yy'?'M'?'d'?'
        if (locale.toString().equalsIgnoreCase("zh_hk")) {
            // Expected application Date Format for Chinese (Hong Kong) locale type
            return "yyyy'MM'dd";
        }
        // Replacing all d|m|y OR Gy with dd|MM|yyyy as per the locale date pattern
        localeDatePattern = localeDatePattern.replaceAll("d{1,2}", "dd").replaceAll(
                "M{1,2}", "MM").replaceAll("y{1,4}|Gy", "yyyy");
        // Replacing all blank spaces in the locale date pattern
        localeDatePattern = localeDatePattern.replace(" ", "");
        // Validating the date pattern length to remove any extract characters
        if (localeDatePattern.length() > 10) {
            // Keeping the standard length as expected by the application
            localeDatePattern = localeDatePattern.substring(0, 10);
        }
        return localeDatePattern;
    }
    

提交回复
热议问题