constructNow.mjs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { constructFrom } from "./constructFrom.mjs";
  2. /**
  3. * @name constructNow
  4. * @category Generic Helpers
  5. * @summary Constructs a new current date using the passed value constructor.
  6. * @pure false
  7. *
  8. * @description
  9. * The function constructs a new current date using the constructor from
  10. * the reference date. It helps to build generic functions that accept date
  11. * extensions and use the current date.
  12. *
  13. * It defaults to `Date` if the passed reference date is a number or a string.
  14. *
  15. * @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).
  16. *
  17. * @param date - The reference date to take constructor from
  18. *
  19. * @returns Current date initialized using the given date constructor
  20. *
  21. * @example
  22. * import { constructNow, isSameDay } from 'date-fns'
  23. *
  24. * function isToday<DateType extends Date>(
  25. * date: DateType | number | string,
  26. * ): boolean {
  27. * // If we were to use `new Date()` directly, the function would behave
  28. * // differently in different timezones and return false for the same date.
  29. * return isSameDay(date, constructNow(date));
  30. * }
  31. */
  32. export function constructNow(date) {
  33. return constructFrom(date, Date.now());
  34. }
  35. // Fallback for modularized imports:
  36. export default constructNow;