sub.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { constructFrom } from "./constructFrom.js";
  2. import { subDays } from "./subDays.js";
  3. import { subMonths } from "./subMonths.js";
  4. /**
  5. * The {@link sub} function options.
  6. */
  7. /**
  8. * @name sub
  9. * @category Common Helpers
  10. * @summary Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date.
  11. *
  12. * @description
  13. * Subtract the specified years, months, weeks, days, hours, minutes and seconds from the given date.
  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. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  17. *
  18. * @param date - The date to be changed
  19. * @param duration - The object with years, months, weeks, days, hours, minutes and seconds to be subtracted
  20. * @param options - An object with options
  21. *
  22. * | Key | Description |
  23. * |---------|------------------------------------|
  24. * | years | Amount of years to be subtracted |
  25. * | months | Amount of months to be subtracted |
  26. * | weeks | Amount of weeks to be subtracted |
  27. * | days | Amount of days to be subtracted |
  28. * | hours | Amount of hours to be subtracted |
  29. * | minutes | Amount of minutes to be subtracted |
  30. * | seconds | Amount of seconds to be subtracted |
  31. *
  32. * All values default to 0
  33. *
  34. * @returns The new date with the seconds subtracted
  35. *
  36. * @example
  37. * // Subtract the following duration from 15 June 2017 15:29:20
  38. * const result = sub(new Date(2017, 5, 15, 15, 29, 20), {
  39. * years: 2,
  40. * months: 9,
  41. * weeks: 1,
  42. * days: 7,
  43. * hours: 5,
  44. * minutes: 9,
  45. * seconds: 30
  46. * })
  47. * //=> Mon Sep 1 2014 10:19:50
  48. */
  49. export function sub(date, duration, options) {
  50. const {
  51. years = 0,
  52. months = 0,
  53. weeks = 0,
  54. days = 0,
  55. hours = 0,
  56. minutes = 0,
  57. seconds = 0,
  58. } = duration;
  59. const withoutMonths = subMonths(date, months + years * 12, options);
  60. const withoutDays = subDays(withoutMonths, days + weeks * 7, options);
  61. const minutesToSub = minutes + hours * 60;
  62. const secondsToSub = seconds + minutesToSub * 60;
  63. const msToSub = secondsToSub * 1000;
  64. return constructFrom(options?.in || date, +withoutDays - msToSub);
  65. }
  66. // Fallback for modularized imports:
  67. export default sub;