Skip to content

Instantly share code, notes, and snippets.

@bhaireshm
Last active February 24, 2025 09:25
Show Gist options
  • Save bhaireshm/fef9b06ed69780a99d0ed429232dfde1 to your computer and use it in GitHub Desktop.
Save bhaireshm/fef9b06ed69780a99d0ed429232dfde1 to your computer and use it in GitHub Desktop.
Calculates the difference between two dates in days, hours and in minutes.
/**
* @param {Date} from
* @param {Date} to
*/
function dateDiff(from, to) {
from = new Date(from);
to = new Date(to);
var diffMs = to - from; // milliseconds between from & to
var diffDays = Math.floor(diffMs / 86400000); // days
var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
var str = "";
str += diffDays ? diffDays + "d " : "";
str += diffHrs ? diffHrs + "h" : "";
str += diffMins ? " " + diffMins + "m" : "";
return {
short: str.trimEnd().trimStart().replace(/ {2}/g, " "),
full: diffDays + " day(s) " + diffHrs + " hours, " + diffMins + " minutes",
days: diffDays,
hours: diffHrs,
minutes: diffMins,
};
}
@bhaireshm
Copy link
Author

ez.js is more than just a library; it's a coding companion that simplifies complex tasks. Whether you're dealing with arrays, numbers, objects, or strings, ez.js has got your back! Say goodbye to coding hassles and hello to streamlined JavaScript magic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment