Search code examples
javaandroidkotlincalendarview

LocaleDateTime.dayOfWeek return me wrong value


I have a calendarView, here's my code

binding.calendarView.setOnDateChangeListener(CalendarView.OnDateChangeListener { view, year, month, dayOfMonth ->
            Toast.makeText(applicationContext, "$dayOfMonth/$month/$year", Toast.LENGTH_LONG).show()
            var selectedDate = LocalDateTime.of(year, month, dayOfMonth, 0, 0)
            val weekdayValue = selectedDate.dayOfWeek.value
            val weekdayName = selectedDate.dayOfWeek.name
        })

When I tap on Monday, weekdayValue = 5 and weekdayName = "Friday". When I tap on Wednesday, weekdayValue = 7 and weekdayName = "Sunday".

The first day of week in my calendarView is 2, so Monday. The Toast show me the good values.

What is the problem ?


Solution

  • CalendarView unfortunately uses 0-based months (January is 0) and LocalDateTime uses 1-based months (January is 1). You need to use LocalDateTime.of(year, month + 1, dayOfMonth, 0, 0).