Back to Blog

Kotlin: Get the date of this Saturday

Sandy LaneSandy Lane

Video: Kotlin: Get the date of this Saturday by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin: Get the Date of This Saturday

In Kotlin, you can easily calculate the date of the upcoming Saturday based on the current date. This is useful for scheduling tasks or displaying weekend-specific information. By using the java.time API, you can handle dates and times in a clear and concise way.

Code

import java.time.DayOfWeek
import java.time.LocalDate
import java.time.temporal.TemporalAdjusters

fun getThisSaturdayDate(): LocalDate {
  val today = LocalDate.now()
  // Adjust to the upcoming or current Saturday
  return today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY))
}

fun main() {
  val saturday = getThisSaturdayDate()
  println("This Saturday's date is: $saturday")
}

Key Points

  • Use java.time.LocalDate to work with dates without time components.
  • TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY) finds this or next Saturday.
  • LocalDate.now() returns the current date according to the system clock.
  • This approach handles cases where today is already Saturday correctly.