Androrider Androrider - 2 months ago 11
Android Question

Get preferred date format string of Android system

Does anybody know how to get the format string used by the system when formatting a date using

DateFormat.getLongDateFormat(Context context).format(Date date)

Answer

I wrote a method to detect this format string. ( work for my case).

public static String getDateFormat(Context context){
        // 25/12/2013
        Calendar testDate = Calendar.getInstance();
        testDate.set(Calendar.YEAR, 2013);
        testDate.set(Calendar.MONTH, Calendar.DECEMBER);
        testDate.set(Calendar.DAY_OF_MONTH, 25);

        Format format = android.text.format.DateFormat.getDateFormat(context);
        String testDateFormat = format.format(testDate.getTime());
        String[] parts = testDateFormat.split("/");
        StringBuilder sb = new StringBuilder();
        for(String s : parts){
            if(s.equals("25")){
                sb.append("dd/");
            }
            if(s.equals("12")){
                sb.append("MM/");
            }
            if(s.equals("2013")){
                sb.append("yyyy/");
            }
        }
        return sb.toString().substring(0, sb.toString().length()-1);
    }

Please check the Mark Melling's answer below http://stackoverflow.com/a/18982842/945808 to have better solution. Mine was just a hack long time ago.

Comments