Skip to content

Instantly share code, notes, and snippets.

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 jonathanarbely/defaba2fa349e64971bd9ced67153b50 to your computer and use it in GitHub Desktop.
Save jonathanarbely/defaba2fa349e64971bd9ced67153b50 to your computer and use it in GitHub Desktop.
Get difference between two dates. Number of seconds, minutes, hours and days between two unix timestamps.
var unixTimeBetween = function(d1, d2) {
var today = d2.getTime() / 1000
var diff = Math.abs(d1 - (d2.getTime() / 1000));
var result = diff / (60 * 60 * 24);
console.log('Result: ' + result);
if(result * 24 * 60 * 60 < 60)
console.log('Seconds ago: ' + Math.trunc(result * 24 * 60 * 60));
else if(result * 24 * 60 < 60)
console.log('Minutes ago: ' + Math.trunc(result * 24 * 60));
else if(result < 1)
console.log('Hours ago: ' + Math.trunc(result * 24));
else
console.log('Days ago: ' + Math.trunc(result));
};
var d1 = 1579140511; // Some other Date (in the past)
var d2 = new Date(); // Today
unixTimeBetween(d1, d2);
@jonathanarbely
Copy link
Author

See working demo (open console - F12): https://jsfiddle.net/jarbely/q6xorn97/

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