sub.cjs 2.4 KB

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