startOfDecade.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { toDate } from "./toDate.js";
  2. /**
  3. * The {@link startOfDecade} options.
  4. */
  5. /**
  6. * @name startOfDecade
  7. * @category Decade Helpers
  8. * @summary Return the start of a decade for the given date.
  9. *
  10. * @description
  11. * Return the start of a decade for the given date.
  12. *
  13. * @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).
  14. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  15. *
  16. * @param date - The original date
  17. * @param options - An object with options
  18. *
  19. * @returns The start of a decade
  20. *
  21. * @example
  22. * // The start of a decade for 21 October 2015 00:00:00:
  23. * const result = startOfDecade(new Date(2015, 9, 21, 00, 00, 00))
  24. * //=> Jan 01 2010 00:00:00
  25. */
  26. export function startOfDecade(date, options) {
  27. // TODO: Switch to more technical definition in of decades that start with 1
  28. // end with 0. I.e. 2001-2010 instead of current 2000-2009. It's a breaking
  29. // change, so it can only be done in 4.0.
  30. const _date = toDate(date, options?.in);
  31. const year = _date.getFullYear();
  32. const decade = Math.floor(year / 10) * 10;
  33. _date.setFullYear(decade, 0, 1);
  34. _date.setHours(0, 0, 0, 0);
  35. return _date;
  36. }
  37. // Fallback for modularized imports:
  38. export default startOfDecade;