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 > 0) return floor + "d";
result *= 24;
floor = Math.floor(result);
if (floor > 0) return floor + "h";
result *= 60;
floor = Math.floor(result);
if (floor > 0) return floor + "min";
result *= 60;
floor = Math.floor(result);
if (floor > 0) return floor + "sec";
}
Math.floor
once? You're multiplying by whole numbers. \$\endgroup\$