简体   繁体   中英

How to get Sunday, Monday … and Saturday String in the language of the android system?

I want to get Sunday, Monday, Tuesday, Wednesday, Thursday, Friday and Saturday String of the locale of the system. I have the code:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
String SundayString = sdf.format(cal.getTime());

This code can get Sunday. But I have to do it seven times to get all strings I need.

I consider another code below:

Calendar cal = Calendar.getInstance();
String[] weekString = new String[7]
for(int i=1;i<=7;++i){
    cal.set(Calendar.DAY_OF_WEEK, i);
    SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
    weekString[i-1] = sdf.format(cal.getTime());
}

It is work because SUNDAY~SATURDAY are 1~7 but it is not a good code I think because if Android change the definition of the constant variable this code will not execute well.

Is there any other good and elegent way to do?

you can use DateFormatSymbols

DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(context.getResources().getConfiguration().locale);
Log.i("DAYS", " " + Arrays.asList(dateFormatSymbols. getWeekdays());

I don't know how many languages you are supporting but if its a few you could add the actual strings in the values folder.

So for Spanish eg

in values-es you would have an array of strings

For example, in your strings.xml:

<string-array name="days_of_the_week">
    <item>Monday in Spanish</item>
    <item>Tuesday in Spanish</item>
</string-array>

String[] days = getResources().getStringArray(R.array.days_of_the_week)

Then get them from the array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM