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

How to Calculate a Date Range Given a Week Number in Golang?

Linda Hamilton
Release: 2024-12-31 10:01:08
Original
758 people have browsed it

How to Calculate a Date Range Given a Week Number in Golang?

Date Range by Week Number in Golang

Background:

Time.ISOWeek() returns the week number that starts on Monday. This article demonstrates how to obtain the date range for a given week, assuming it starts from Sunday.

Solution:

  1. Calculate the Week Start:

Start by aligning to the first day of the week (Monday) from the middle of the year. Corrigate by adding days based on the week difference multiplied by 7.

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
}
Copy after login
  1. Calculate the Week Range:

To get the date range, determine the week's first day and add 6 days to obtain the last day.

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

Example:

fmt.Println(WeekRange(2018, 1))
fmt.Println(WeekRange(2018, 2))
fmt.Println(WeekRange(2019, 1))
fmt.Println(WeekRange(2019, 2))
Copy after login

Output (try it on the Go Playground):

2018-01-01 00:00:00 +0000 UTC 2018-01-07 00:00:00 +0000 UTC
2018-01-08 00:00:00 +0000 UTC 2018-01-14 00:00:00 +0000 UTC
2018-12-31 00:00:00 +0000 UTC 2019-01-06 00:00:00 +0000 UTC
2019-01-07 00:00:00 +0000 UTC 2019-01-13 00:00:00 +0000 UTC
Copy after login

Additional Note:

The WeekStart() function manages out-of-range weeks. Weeks outside the year range are interpreted as the last or first week of the previous or subsequent year, respectively.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template