Note: The first week of the year is the one that has 4 January in it.
I'm trying to solve this problem where I want to know the week number given a date. And it can be solve by following the next steps.
- Subtract the weekday number from the ordinal day of the year.
- Add 10.
- Divide by 7, discard the remainder.
3.a) If the week number thus obtained equals 0, it means that the given date belongs to the preceding (week-based) year. 3.b) If a week number of 53 is obtained, one must check that the date is not actually in week 1 of the following year.
So using kotlinx.datetime.*, how to get the total number of weeks in the current year so I can solve this method?
My code:
fun getWeekOfYear(date: LocalDate): Int {
val week: Int = (10 + date.dayOfYear - date.dayOfWeek.ordinal) / 7
return if (week in 1..52) {
week
} else if (week < 1) {
// return if week 53 or week 52 of the past year?
} else if (week < 52) {
// return if week 53 or week 1 of the next year?
}
}
I tried using Java Calendar and it is easy to do, but as we can't use Java because is a KMM project it doesn't work.

DateTimePeriodto get a diff between two dates. You should be able to use one date as first date of the year and another date as what's passed in above function. Then you'd have a diff in hours/minutes/days etc. That should help in calculating the week.