May 30, 2015

Golang: Reverse ISOWeek, get the date of the first day of ISO week

If you work with weeknummers, you can find the weeknumber of a date with the Golang function time.ISOWeek. However you wish to get the first date of a week, there is no such function in Google Go. So let's write it our selfs:

func FirstDayOfISOWeek(year int, week int, timezone *time.Location) time.Time {
date := time.Date(year, 0, 0, 0, 0, 0, 0, timezone)
isoYear, isoWeek := date.ISOWeek()

// iterate back to Monday
for date.Weekday() != time.Monday {
date = date.AddDate(0, 0, -1)
isoYear, isoWeek = date.ISOWeek()
}

// iterate forward to the first day of the first week
for isoYear < year {
date = date.AddDate(0, 0, 7)
isoYear, isoWeek = date.ISOWeek()
}

// iterate forward to the first day of the given week
for isoWeek < week {
date = date.AddDate(0, 0, 7)
isoYear, isoWeek = date.ISOWeek()
}

return date
}

2 comments on “Golang: Reverse ISOWeek, get the date of the first day of ISO week”

  1. Hi, here is my simpler and a bit faster version:
    func getFirstDayOfISOweek(year int, week int) time.Time {
    answer := time.Date(year, 1, -14, 0, 0, 0, 0, time.Local)
    answer = answer.Local().AddDate(0, 0, (week)*7)
    _, tw := answer.Local().ISOWeek()
    for tw != week {
    answer = answer.Local().AddDate(0, 0, 1)
    _, tw = answer.Local().ISOWeek()
    }
    return answer
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

XFerion Europe LLP
We build an maintain your software. From web to mobile. From MVP to extended product. Contact us if you wish to discuss a project.
CONTACT US