milliseconds.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { daysInYear } from "./constants.js";
  2. /**
  3. * @name milliseconds
  4. * @category Millisecond Helpers
  5. * @summary
  6. * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds.
  7. *
  8. * @description
  9. * Returns the number of milliseconds in the specified, years, months, weeks, days, hours, minutes and seconds.
  10. *
  11. * One years equals 365.2425 days according to the formula:
  12. *
  13. * > Leap year occurs every 4 years, except for years that are divisible by 100 and not divisible by 400.
  14. * > 1 mean year = (365+1/4-1/100+1/400) days = 365.2425 days
  15. *
  16. * One month is a year divided by 12.
  17. *
  18. * @param duration - The object with years, months, weeks, days, hours, minutes and seconds to be added.
  19. *
  20. * @returns The milliseconds
  21. *
  22. * @example
  23. * // 1 year in milliseconds
  24. * milliseconds({ years: 1 })
  25. * //=> 31556952000
  26. *
  27. * // 3 months in milliseconds
  28. * milliseconds({ months: 3 })
  29. * //=> 7889238000
  30. */
  31. export function milliseconds({
  32. years,
  33. months,
  34. weeks,
  35. days,
  36. hours,
  37. minutes,
  38. seconds,
  39. }) {
  40. let totalDays = 0;
  41. if (years) totalDays += years * daysInYear;
  42. if (months) totalDays += months * (daysInYear / 12);
  43. if (weeks) totalDays += weeks * 7;
  44. if (days) totalDays += days;
  45. let totalSeconds = totalDays * 24 * 60 * 60;
  46. if (hours) totalSeconds += hours * 60 * 60;
  47. if (minutes) totalSeconds += minutes * 60;
  48. if (seconds) totalSeconds += seconds;
  49. return Math.trunc(totalSeconds * 1000);
  50. }
  51. // Fallback for modularized imports:
  52. export default milliseconds;