Skip to content

Instantly share code, notes, and snippets.

@hachibu
Last active October 21, 2023 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hachibu/d0db9ee8a98ee90cb41ab79e585383f8 to your computer and use it in GitHub Desktop.
Save hachibu/d0db9ee8a98ee90cb41ab79e585383f8 to your computer and use it in GitHub Desktop.
const dateDiff = (startDate, endDate) => {
const startUTC = dateToUTC(startDate);
const endUTC = dateToUTC(endDate);
const diffMilliseconds = endUTC - startUTC;
const millisecondsPerDay = 1000 * 60 * 60 * 24;
const diffDays = diffMilliseconds / millisecondsPerDay;
const [years, yearsRem] = floordivmod(diffDays, 365);
const [months, monthsRem] = floordivmod(yearsRem, 30);
const [days, daysRem] = floormod(monthsRem);
const [hours, hoursRem] = floormod(daysRem * 24);
const [minutes, minutesRem] = floormod(hoursRem * 60);
const [seconds, secondsRem] = floormod(minutesRem * 60);
const [milliseconds] = floormod(secondsRem * 1000);
return { years, months, days, hours, minutes, seconds, milliseconds };
};
const dateToUTC = (date) =>
Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
);
const floordivmod = (n, m) => {
let q = Math.floor(n / m);
let r = n % m;
return [q, r];
};
const floormod = (n) => {
if (n === 0) {
return [0, 0];
}
let q = Math.floor(n);
let r = n % q;
return [q, r];
};
const main = () => {
const args = process.argv.slice(2);
let startDate, endDate;
if (args.length === 1) {
startDate = new Date(args[0]);
endDate = new Date();
} else if (args.length === 2) {
startDate = new Date(args[0]);
endDate = new Date(args[1]);
}
if (startDate && endDate) {
const diff = dateDiff(startDate, endDate);
console.log(diff);
}
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment