sub.js 2.3 KB

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