Kotlin: Get the date for the first day of the week
Video: Kotlin: Get the date for the first day of the week by Taught by Celeste AI - AI Coding Coach
Watch full page →Kotlin: Get the Date for the First Day of the Week
Working with dates in Kotlin often requires finding the start of the week for a given date. This is useful for calendar apps, scheduling, or reporting features. Kotlin’s java.time API makes it straightforward to calculate the date corresponding to the first day of the current week.
Code
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.temporal.TemporalAdjusters
fun getFirstDayOfWeek(date: LocalDate): LocalDate {
// Adjust the given date to the previous or same Monday (start of the week)
return date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
}
fun main() {
val today = LocalDate.now()
val firstDay = getFirstDayOfWeek(today)
println("Today: $today")
println("First day of this week: $firstDay")
}
Key Points
- Use java.time.LocalDate to represent dates without time or timezone concerns.
- TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY) finds the Monday on or before the given date.
- This approach is locale-independent but assumes Monday as the week start; adjust if needed.
- Calling this function with today’s date returns the current week’s first day.