Home > Back-end >  How to implement a broadcast calendar in Kotlin (or Java)
How to implement a broadcast calendar in Kotlin (or Java)

Time:09-14

I'm trying to write an application that calculates the week number according to the broadcast calendar. The Wikipedia definition says:

Every week in the broadcast calendar starts on a Monday and ends on a Sunday [...] the first week of every broadcast month always contains the Gregorian calendar first of the month

So I thought I could use WeekFields class and tried implementing it this way:

    val broadcastCalendar = WeekFields.of(DayOfWeek.MONDAY, 1)
    val march1 = LocalDate.of(2022, 3, 1)
    val weekOfMarch1 = march1.get(broadcastCalendar.weekOfYear())
    println("March 1 2022: $weekOfMarch1") // 10

This works fine most of the time but when trying to figure out the week numbers at the end and beginning of the year it fails:

    val lastDayOf2022 = LocalDate.of(2022, 12, 31)
    val lastWeekOf2022 = lastDayOf2022.get(broadcastCalendar.weekOfYear())

    val firstDayOf2023 = LocalDate.of(2023, 1, 1)
    val firstWeekOf2023 = firstDayOf2023.get(broadcastCalendar.weekOfYear())

    println("last week of 2022: $lastWeekOf2022") // 53
    println("first week of 2023: $firstWeekOf2023") // 1

According to Wikipedia's definition, the last week of 2022 should be 52 (Dec 19 - Dec 25) and the first one in 2023 should be 1 (Dec 26 - Jan 1) - see here.

How can I use WeekFields (or any other way) to fetch the correct week number?

CodePudding user response:

From these quotes in the Wikipedia article, it seems like this calendar system uses a week-based year.

For example, if January 1 falls on a Saturday, then the broadcast calendar year would begin on the preceding Monday, December 27.

Broadcast calendar years can have either 52 or 53 weeks.

Because of this is, you should use weekOfWeekBasedYear:

val broadcastCalendar = WeekFields.of(DayOfWeek.MONDAY, 1)
val lastDayOf2022 = LocalDate.of(2022, 12, 31)
val lastWeekOf2022 = march1.get(broadcastCalendar.weekOfWeekBasedYear())
println(lastWeekOf2022) // 1

This represents the concept of the count of weeks within the year where weeks start on a fixed day-of-week, such as Monday and each week belongs to exactly one year.

  • Related