I have a compose view that is given a month and year. I want to find the first weekday of the given month/year combo in the idiomatic Kotlin way. This is what I have so far:
fun CalendarMonthView(
month: Month = LocalDate.now().month,
year: Int = LocalDate.now().year
) {
// ...
val weekDayNames = DateFormatSymbols.getInstance().weekdays
val firstWeekdayOfMonth = //type annotation in IntelliJ: (Calendar .. Calendar?)
Calendar.getInstance().also {
it.set(Calendar.DATE, 1)
it.set(Calendar.MONTH, month.value)
it.set(Calendar.YEAR, year)
it.set(Calendar.DAY_OF_MONTH, 1)
// does not evaluate to a string?
weekDayNames[it.get(Calendar.DAY_OF_WEEK)]
}
// ...
}
Is there an idiomatic way to do this instead of something like:
val cal = Calendar.getInstance()
cal.set(Calendar.DATE, 1)
cal.set(Calendar.MONTH, month.value)
cal.set(Calendar.YEAR, year)
cal.set(Calendar.DAY_OF_MONTH, 1)
val firstDay = weekDayNames[cal.get(Calendar.DAY_OF_WEEK)] // type annotation: String
CodePudding user response:
You can do something like:
val month = LocalDate.now().month
val year = LocalDate.now().year
val dayOfWeek = LocalDate.of(year, month, 1).dayOfWeek
println(dayOfWeek.name) // prints "FRIDAY" for April 2022