Home > Software engineering >  Idiomatic way to get list of Locale appropriate short weekday names
Idiomatic way to get list of Locale appropriate short weekday names

Time:09-02

I am displaying a weekdays header in a custom calendar widget. For prototyping, I just used:

listOf("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")

Now I want to do it in a Locale savvy way. I tried

DateFormatSymbols().shortWeekdays

but discovered in a round about way that that surprisingly returns an array of 8 values (so that Sunday can be accessed at 1 apparently). I could slice that from 1..7, but that seems hacky. Is there a current idiomatic way to get a list of short weekday names for a Compose/Kotlin app?

CodePudding user response:

If you look for a solution which is "the most correct", you don't want to use any shortcuts or assumptions on the structure/ordering inside shortWeekdays, then note that technically speaking, you should access the data in this array using Calendar.* constants.

If you already use 0 as Sunday and 6 as Saturday across your application then you can either change the logic of your application and use above constants; or the most correct solution would be to first map your day of week to the corresponding constant and then use it. You can do it like this:

private val MY_DAY_OF_WEEK_TO_CALENDAR = arrayOf(Calendar.SUNDAY, Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY)

fun DateFormatSymbols.getMyDayOfWeek(myDayOfWeek: Int) = shortWeekdays[MY_DAY_OF_WEEK_TO_CALENDAR[myDayOfWeek]]

This way we don't need slicing, we don't need to assume that the first element is not needed, etc.

Alternatively, if you don't control the moment where the specific weekday is acquired, but instead you would like to create an array once and then use it multiple times with your week of day, then you can use this:

fun DateFormatSymbols.getShortWeekdaysByMyDayOfWeek() = Array(7) { shortWeekdays[MY_DAY_OF_WEEK_TO_CALENDAR[it]] }

You use these functions like this:

fun main() {
    val format = DateFormatSymbols()
    println(format.getMyDayOfWeek(1)) // Mon
    println(format.getShortWeekdaysByMyDayOfWeek()[1]) // Mon
}
  • Related