androidkotlinkotlin-multiplatformkotlin-multiplatform-mobilekotlinx-datetime

Getting days of current week using kotlinx-datetime KMM


How can I get the dates of the current week using kotlinx.datetime KMM library?

eg. I want to get a list of current week's date like:

("Monday, 07", "Tuesday, 08", "Wednesday, 09", ... )

This is a similar impementation using Calendar:

fun getDaysOfWeek(): Array<String?> {
        val dateFormat = SimpleDateFormat("EEEEE\ndd", Locale.getDefault())
        val calendar = Calendar.getInstance()
        calendar.firstDayOfWeek = Calendar.MONDAY
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)

        val days = arrayOfNulls<String>(7)
        for (i in 0..6) {
            days[i] = dateFormat.format(calendar.time)
            calendar.add(Calendar.DAY_OF_MONTH, 1)
        }

        return days
    }

Solution

  • val today = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date
    val days = mutableListOf<LocalDate>()
    val firstWeekDay = today.daysShift(-DayOfWeek.values().indexOf(today.dayOfWeek))
    for (i in 0 until DayOfWeek.values().count()) {
        days.add(firstWeekDay.daysShift(i))
    }
    val dayStrings = days.map { "${it.dayOfWeek}, ${it.dayOfMonth}" }
    println("$dayStrings")
    
    fun LocalDate.daysShift(days: Int): LocalDate = when {
        days < 0 -> {
            minus(DateTimeUnit.DayBased(-days))
        }
        days > 0 -> {
            plus(DateTimeUnit.DayBased(days))
        }
        else -> this
    }