sub.mjs 2.3 KB

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