Home >Backend Development >Golang >How to Calculate the Date Range for a Given Week Number in Go?

How to Calculate the Date Range for a Given Week Number in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 02:23:10982browse

How to Calculate the Date Range for a Given Week Number in Go?

Date Range by Week Number in Go

Given the week number obtained using the provided Week function, this article explores how to determine the corresponding date range starting on Sunday.

Foreword: ISO Week and Custom Handling

It's important to note that the standard ISO Week starts on Monday. To adapt to this convention, the following approach handles weeks starting on either Monday or Sunday.

Week Range Determination

To determine the date range of a week, we:

  1. Start from the middle of the year (July 1st).
  2. Align to the first day of the week (Monday by default).
  3. Get the week number of this time value.
  4. Corrigate by adding or subtracting days based on the week difference.

Implementation:

func WeekStart(year, week int) time.Time {
    t := time.Date(year, 7, 1, 0, 0, 0, 0, time.UTC)
    if wd := t.Weekday(); wd == time.Sunday {
        t = t.AddDate(0, 0, -6)
    } else {
        t = t.AddDate(0, 0, -int(wd)+1)
    }
    _, w := t.ISOWeek()
    t = t.AddDate(0, 0, (week-w)*7)
    return t
}

Example Usage:

fmt.Println(WeekStart(2018, 1))
// Output: 2018-01-01 00:00:00 +0000 UTC
fmt.Println(WeekStart(2018, 2))
// Output: 2018-01-08 00:00:00 +0000 UTC

Handling Out-of-Range Weeks:

This implementation handles out-of-range weeks gracefully, interpreting them as weeks of the previous or next year.

Determining End of Week:

To obtain the last day of the week, simply add 6 days to the week's first day:

func WeekRange(year, week int) (start, end time.Time) {
    start = WeekStart(year, week)
    end = start.AddDate(0, 0, 6)
    return
}

The above is the detailed content of How to Calculate the Date Range for a Given Week Number in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn