Date range by week number

Asked

Viewed 44 times

1

With this simple function, I can get the week number. Now, with the week number, how can I get the date range, started on Sunday?

import (
    "fmt"
    "time"
)

func main() {
    Week(time.Now().UTC())
}

func Week(now time.Time) string {
    _, thisWeek := now.ISOWeek()
    return "S" + strconv.Itoa(thisWeek)
}`

All help is welcome. Thank you.

  • 1

    Welcome David! This is Stackoverflow in English. Translate, format your question so we can help you!

1 answer

0

My Portuguese is not good, sorry.

You can use time.(Time).Truncate and then change the result:

const (
    day       = 24 * time.Hour
    sevenDays = 7 * day
)

// weekSun returns the beginning and the end of the week of the time t in UTC,
// using Sunday as the first day.
func weekSun(t time.Time) (start, end time.Time) {
    start = t.Truncate(sevenDays).Add(-day)
    end = start.Add(sevenDays - 1)
    return start, end
}

Playground: https://play.golang.org/p/EJMsriS0qYa.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.