0

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.

  1. Subtract the weekday number from the ordinal day of the year.
  2. Add 10.
  3. 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.

enter image description here

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.

1
  • In Kotlin, you can use DateTimePeriod to 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. Commented Jan 16, 2023 at 14:56

1 Answer 1

-1

I'm using this extension function to get the week using kotlinx-datetime:

    fun LocalDate.getWeekNumber(): Int {
    val firstDayOfYear = LocalDate(year, 1, 1)
    val daysFromFirstDay = dayOfYear - firstDayOfYear.dayOfYear
    val firstDayOfYearDayOfWeek = firstDayOfYear.dayOfWeek.value
   val adjustment = when {
        firstDayOfYearDayOfWeek <= 4 -> firstDayOfYearDayOfWeek - 1 
        else -> 8 - firstDayOfYearDayOfWeek 
    }
    return (daysFromFirstDay + adjustment) / 7 + 1
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.