Search code examples
androidlocalesimpledateformat

How to get date and time formatted using the device locale language?


I am trying to get the date and time using Date(), and display it in a TextView. is it possible to format it using the device locale?

for Example:

Arabic locale device خميس 2\2\2015

Turkish locale device Çar 2\2\2014

English locale device Wed 2\2\2014


Solution

  • If you want to convert a java.util.Date into a string, you might use the SimpleDateFormat class. The second constructor of this class takes an argument of the type Locale. With Locale.getDefault() you can get the default locale of the device, if it is not set or found it will give the locale for en_Us.

    Here's a litte sample code:

    public static void main(String [] args){
        DateFormat df = new SimpleDateFormat("yyyy/MMM/dd EE", Locale.getDefault());
        Date today = Calendar.getInstance().getTime();
        String reportDate = df.format(today);
        System.out.println(reportDate);
    }
    

    You can also set the Local exclipcity, for example Locale.CHINESE or you can iterate through an array of locals, which are available on the current device (see Locale.getAvailableLocales()).

    Hope I could help you!