Skip to content

Instantly share code, notes, and snippets.

@bseib
Created May 22, 2022 21:32
Show Gist options
  • Save bseib/833935eb4ff633e8a2e0bac71a26f185 to your computer and use it in GitHub Desktop.
Save bseib/833935eb4ff633e8a2e0bac71a26f185 to your computer and use it in GitHub Desktop.
Kotlin `LocalDate` extension functions to shift to a particular weekday, and US Holidays
import java.time.DayOfWeek
import java.time.LocalDate
fun LocalDate.lastDayOfWeek(dow: DayOfWeek): LocalDate {
val minus = (this.dayOfWeek.value + 7 - dow.value) % 7
return this.minusDays(minus.toLong())
}
fun LocalDate.firstDayOfWeek(dow: DayOfWeek): LocalDate {
val plus = (dow.value + 7 - this.dayOfWeek.value) % 7
return this.plusDays(plus.toLong())
}
fun LocalDate.secondDayOfWeek(dow: DayOfWeek): LocalDate {
return this.firstDayOfWeek(dow).plusDays(7)
}
fun LocalDate.thirdDayOfWeek(dow: DayOfWeek): LocalDate {
return this.firstDayOfWeek(dow).plusDays(14)
}
fun LocalDate.fourthDayOfWeek(dow: DayOfWeek): LocalDate {
return this.firstDayOfWeek(dow).plusDays(21)
}
import firstDayOfWeek
import fourthDayOfWeek
import lastDayOfWeek
import secondDayOfWeek
import thirdDayOfWeek
import java.time.DayOfWeek
import java.time.LocalDate
object UnitedStatesFederalHolidays {
fun newYearsDay(year: Int) = LocalDate.of(year, 1, 1)
fun martinLutherKingJrBirthday(year: Int) = LocalDate.of(year, 1, 1).thirdDayOfWeek(DayOfWeek.MONDAY)
fun washingtonBirthday(year: Int) = LocalDate.of(year, 2, 1).thirdDayOfWeek(DayOfWeek.MONDAY)
fun memorialDay(year: Int) = LocalDate.of(year, 5, 31).lastDayOfWeek(DayOfWeek.MONDAY)
fun juneteenthDay(year: Int) = LocalDate.of(year, 6, 19)
fun independenceDay(year: Int) = LocalDate.of(year, 7, 4)
fun laborDay(year: Int) = LocalDate.of(year, 9, 1).firstDayOfWeek(DayOfWeek.MONDAY)
fun columbusDay(year: Int) = LocalDate.of(year, 10, 1).secondDayOfWeek(DayOfWeek.MONDAY)
fun veteransDay(year: Int) = LocalDate.of(year, 11, 11)
fun thanksgivingDay(year: Int) = LocalDate.of(year, 11, 1).fourthDayOfWeek(DayOfWeek.THURSDAY)
fun christmasDay(year: Int) = LocalDate.of(year, 12, 25)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment