Get the difference between two dates, in the most convenient unit I use the following code in Javascript to get the difference between two Date objects. I want the result to return the difference in:


seconds if the result is less than 60 secs
minutes if the result is less than 60 mins
hours if the result is less than 24 hours
days otherwise


The code is very long and I see lots of code duplication. Isn't there a smarter/shorter way to do this (without using a library)?

function dateDiff(a, b) {
  let utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate(), a.getUTCHours(), a.getUTCMinutes(), a.getUTCSeconds());
  let utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate(), b.getUTCHours(), b.getUTCMinutes(), b.getUTCSeconds());

  let result = (utc2 - utc1) / (1000 * 60 * 60 * 24);
  let floor = Math.floor(result);
  if (floor &gt; 0) return floor + "d";

  result *= 24;
  floor = Math.floor(result);
  if (floor &gt; 0) return floor + "h";

  result *= 60;
  floor = Math.floor(result);
  if (floor &gt; 0) return floor + "min";

  result *= 60;
  floor = Math.floor(result);
  if (floor &gt; 0) return floor + "sec";
}
Use getTime instead of the UTC transformation it'll return the timeStamp.

So your diff would be:

b.getTime() - a.getTime()


This will give you the milliseconds if you want the seconds you would divide it by 1000 so you would get:

var secondsDiff = (b.getTIme() - a.getTime())/1000


Then for the return 

if (secondsDiff &gt; 86400)  { 
 return Math.floor(secondsDiff/86400) + ' D'
}
if (secondsDiff &gt; 3600)  { 
 return Math.floor(secondsDiff/3600) + ' h'
}
if (secondsDiff &gt; 60)  { 
 return Math.floor(secondsDiff/60) + ' min'
}
if (secondsDiff &gt; 0) { 
 return secondsDiff + ' sec'
}