WeeksSinceEpoch gets the weeks since the epoch for a given time. This is a 0-indexed number of weeks since the epoch (Monday). The timezone embedded in the time object is used to determine the epoch.
(now time.Time)
| 295 | // |
| 296 | // The timezone embedded in the time object is used to determine the epoch. |
| 297 | func WeeksSinceEpoch(now time.Time) (int64, error) { |
| 298 | epoch := TemplateAutostopRequirementEpoch(now.Location()) |
| 299 | if now.Before(epoch) { |
| 300 | return 0, xerrors.New("coder server system clock is incorrect, cannot calculate template autostop requirement") |
| 301 | } |
| 302 | |
| 303 | // This calculation needs to be done using YearDay, as dividing by the |
| 304 | // amount of hours is impacted by daylight savings. Even though daylight |
| 305 | // savings is usually only an hour difference, this calculation is used to |
| 306 | // get the current week number and could result in an entire week getting |
| 307 | // skipped if the calculation is off by an hour. |
| 308 | // |
| 309 | // Old naive algorithm: weeksSinceEpoch := int64(since.Hours() / (24 * 7)) |
| 310 | |
| 311 | // Get days since epoch. Start with a negative number of days, as we want to |
| 312 | // subtract the YearDay() of the epoch itself. |
| 313 | days := -epoch.YearDay() |
| 314 | for i := epoch.Year(); i < now.Year(); i++ { |
| 315 | startOfNextYear := time.Date(i+1, 1, 1, 0, 0, 0, 0, now.Location()) |
| 316 | if startOfNextYear.Year() != i+1 { |
| 317 | return 0, xerrors.New("overflow calculating weeks since epoch") |
| 318 | } |
| 319 | endOfThisYear := startOfNextYear.AddDate(0, 0, -1) |
| 320 | if endOfThisYear.Year() != i { |
| 321 | return 0, xerrors.New("overflow calculating weeks since epoch") |
| 322 | } |
| 323 | |
| 324 | days += endOfThisYear.YearDay() |
| 325 | } |
| 326 | // Add this year's days. |
| 327 | days += now.YearDay() |
| 328 | |
| 329 | // Ensure that the number of days is positive. |
| 330 | if days < 0 { |
| 331 | return 0, xerrors.New("overflow calculating weeks since epoch") |
| 332 | } |
| 333 | |
| 334 | // Divide by 7 to get the number of weeks. |
| 335 | weeksSinceEpoch := int64(days / 7) |
| 336 | return weeksSinceEpoch, nil |
| 337 | } |
| 338 | |
| 339 | // GetMondayOfWeek gets the Monday (0:00) of the n-th week since epoch. |
| 340 | func GetMondayOfWeek(loc *time.Location, n int64) (time.Time, error) { |