startOfDecade.mjs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { toDate } from "./toDate.mjs";
  2. /**
  3. * @name startOfDecade
  4. * @category Decade Helpers
  5. * @summary Return the start of a decade for the given date.
  6. *
  7. * @description
  8. * Return the start of a decade for the given date.
  9. *
  10. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  11. *
  12. * @param date - The original date
  13. *
  14. * @returns The start of a decade
  15. *
  16. * @example
  17. * // The start of a decade for 21 October 2015 00:00:00:
  18. * const result = startOfDecade(new Date(2015, 9, 21, 00, 00, 00))
  19. * //=> Jan 01 2010 00:00:00
  20. */
  21. export function startOfDecade(date) {
  22. // TODO: Switch to more technical definition in of decades that start with 1
  23. // end with 0. I.e. 2001-2010 instead of current 2000-2009. It's a breaking
  24. // change, so it can only be done in 4.0.
  25. const _date = toDate(date);
  26. const year = _date.getFullYear();
  27. const decade = Math.floor(year / 10) * 10;
  28. _date.setFullYear(decade, 0, 1);
  29. _date.setHours(0, 0, 0, 0);
  30. return _date;
  31. }
  32. // Fallback for modularized imports:
  33. export default startOfDecade;