-1

How can I turn a string containing the year and an iso week date into a time object?

This is how the string I have looks like: 2020-15, where 2020 is the year and 15 is the iso week number. Ideally, I would like to get the first available timestamp of a week (Monday at midnight).

I read through the documentation of the Parse() method here https://golang.org/pkg/time/#Parse, but I cannot figure out how to come up with a layout string of the reference time where the week is taken into account.

  • That is not supported by the `time` package. – Adrian May 22 '20 at 17:00
  • You should be able to draw something up yourself pretty quickly by creating a new `time.Time` on January 1 of the specified year; advancing it to whatever day you want to treat as your canonical start of the week; then adding (7 * weekNumber) days to it. – Adrian May 22 '20 at 17:05

1 Answers1

1

You should be able to draw something up yourself pretty quickly by creating a new time.Time on January 1 of the specified year; advancing it to whatever day you want to treat as your canonical start of the week; then adding (7 * weekNumber) days to it, for example:

t := time.Date(year, 1, 1, 0, 0, 0, 0, location)
offset := (t.Weekday() + 7 - weekStart) % 7
t = t.Add(time.Duration(offset*24) * time.Hour)
t = t.Add(time.Duration((week-1)*7*24) * time.Hour)

Working example: https://play.golang.org/p/EjUpnRZRE6T

Adrian
  • 42,911
  • 6
  • 107
  • 99