date.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. export function getWeekBounds(date: Date) {
  2. const offset = (date.getUTCDay() + 6) % 7
  3. const start = new Date(date)
  4. start.setUTCDate(date.getUTCDate() - offset)
  5. start.setUTCHours(0, 0, 0, 0)
  6. const end = new Date(start)
  7. end.setUTCDate(start.getUTCDate() + 7)
  8. return { start, end }
  9. }
  10. export function getMonthlyBounds(now: Date, subscribed: Date) {
  11. const day = subscribed.getUTCDate()
  12. const hh = subscribed.getUTCHours()
  13. const mm = subscribed.getUTCMinutes()
  14. const ss = subscribed.getUTCSeconds()
  15. const ms = subscribed.getUTCMilliseconds()
  16. function anchor(year: number, month: number) {
  17. const max = new Date(Date.UTC(year, month + 1, 0)).getUTCDate()
  18. return new Date(Date.UTC(year, month, Math.min(day, max), hh, mm, ss, ms))
  19. }
  20. function shift(year: number, month: number, delta: number) {
  21. const total = year * 12 + month + delta
  22. return [Math.floor(total / 12), ((total % 12) + 12) % 12] as const
  23. }
  24. let y = now.getUTCFullYear()
  25. let m = now.getUTCMonth()
  26. let start = anchor(y, m)
  27. if (start > now) {
  28. ;[y, m] = shift(y, m, -1)
  29. start = anchor(y, m)
  30. }
  31. const [ny, nm] = shift(y, m, 1)
  32. const end = anchor(ny, nm)
  33. return { start, end }
  34. }