Home >Backend Development >Golang >How to Get a Date Range Based on Week Number in Go?

How to Get a Date Range Based on Week Number in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-07 05:55:19735browse

How to Get a Date Range Based on Week Number in Go?

Date Range by Week Number in Golang

Resolving Week Number Discrepancies

The time.ISOWeek() function in the Go standard library returns the ISO week number, which begins on Monday. However, it appears you require week numbers based on a Sunday start date.

Custom Utility

To address this issue, let's utilize a custom utility function to obtain the desired date range:

import "time"

func WeekStart(year, week int) time.Time {
    // Align to first day of the week (Sunday) and correct week number
    t := time.Date(year, time.July, 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)
    }
    t = t.AddDate(0, 0, (week-1)*7)
    return t
}

Week Range

If you need both the start and end dates for the specified week, you can use the following function:

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

Sample Output

fmt.Println(WeekRange(2018, 1))
fmt.Println(WeekRange(2018, 52))

Output

2018-01-01 00:00:00 +0000 UTC 2018-01-07 00:00:00 +0000 UTC
2018-12-24 00:00:00 +0000 UTC 2018-12-30 00:00:00 +0000 UTC

Note: This method handles out-of-range weeks by interpreting 0 as the last week of the previous year, -1 as the second to last week of the previous year, and so on.

The above is the detailed content of How to Get a Date Range Based on 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