UNPKG

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