GetNextApplicableMondayOfNWeeks gets the next Monday (0:00) of the next week divisible by n since epoch. If the next applicable week is invalid for any reason, the week after will be used instead (up to 2 attempts). If the current week is divisible by n, then the provided time is returned as is. T
(now time.Time, n int64)
| 363 | // |
| 364 | // The timezone embedded in the time object is used to determine the epoch. |
| 365 | func GetNextApplicableMondayOfNWeeks(now time.Time, n int64) (time.Time, error) { |
| 366 | // Get the current week number. |
| 367 | weeksSinceEpoch, err := WeeksSinceEpoch(now) |
| 368 | if err != nil { |
| 369 | return time.Time{}, xerrors.Errorf("get current week number: %w", err) |
| 370 | } |
| 371 | |
| 372 | // Get the next week divisible by n. |
| 373 | remainder := weeksSinceEpoch % n |
| 374 | week := weeksSinceEpoch + (n - remainder) |
| 375 | if remainder == 0 { |
| 376 | return now, nil |
| 377 | } |
| 378 | |
| 379 | // Loop until we find a week that doesn't fail. This should never loop, but |
| 380 | // we account for failures just in case. |
| 381 | var lastErr error |
| 382 | for i := int64(0); i < 3; i++ { |
| 383 | monday, err := GetMondayOfWeek(now.Location(), week+i) |
| 384 | if err != nil { |
| 385 | lastErr = err |
| 386 | continue |
| 387 | } |
| 388 | |
| 389 | return monday, nil |
| 390 | } |
| 391 | |
| 392 | return time.Time{}, xerrors.Errorf("get next applicable Monday of %v weeks: %w", n, lastErr) |
| 393 | } |
no test coverage detected