Search code examples
androidcalendarlocaledayofweekjava-time

Get weekdays in order by locale


I'm trying to see if we can get the weekdays in order by locale. For example in US locale, we'll start with Sunday, while FR will start with Monday (in the terms of Calendar). To make sense out of it, I'm making an alarm app with the weekdays where the alarm is repeated on certain days -

enter image description here

Here are weekdays are not in ordered that I'm seeing in

new DateFormatSymbols().getShortWeekdays();

0 = ""
1 = "Sun"
2 = "Mon"
3 = "Tue"
4 = "Wed"
5 = "Thu"
6 = "Fri"
7 = "Sat"

0 = ""
1 = "dim."
2 = "lun."
3 = "mar."
4 = "mer."
5 = "jeu."
6 = "ven."
7 = "sam."

Solution

  • java.time

    public static void printWeekdays(Locale loc) {
        WeekFields wf = WeekFields.of(loc);
        DayOfWeek day = wf.getFirstDayOfWeek();
        for (int i = 0; i < DayOfWeek.values().length; i++) {
            System.out.println(day.getDisplayName(TextStyle.SHORT, loc));
            day = day.plus(1);
        }
    }
    

    Let’s try it out:

        printWeekdays(Locale.US);
    

    The output from this call is:

    Sun
    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
    

    Or in French:

        printWeekdays(Locale.FRANCE);
    

    Now Monday/lundi comes first, and in French, of course:

    lun.
    mar.
    mer.
    jeu.
    ven.
    sam.
    dim.
    

    Question: Can I use java.time on Android?

    Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

    • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
    • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
    • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

    Links