HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptMinor

Get the difference between two dates, in the most convenient unit

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thedatesconvenientdifferencetwobetweengetmostunit

Problem

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";
}

Solution

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 > 86400)  { 
 return Math.floor(secondsDiff/86400) + ' D'
}
if (secondsDiff > 3600)  { 
 return Math.floor(secondsDiff/3600) + ' h'
}
if (secondsDiff > 60)  { 
 return Math.floor(secondsDiff/60) + ' min'
}
if (secondsDiff > 0) { 
 return secondsDiff + ' sec'
}

Code Snippets

b.getTime() - a.getTime()
var secondsDiff = (b.getTIme() - a.getTime())/1000
if (secondsDiff > 86400)  { 
 return Math.floor(secondsDiff/86400) + ' D'
}
if (secondsDiff > 3600)  { 
 return Math.floor(secondsDiff/3600) + ' h'
}
if (secondsDiff > 60)  { 
 return Math.floor(secondsDiff/60) + ' min'
}
if (secondsDiff > 0) { 
 return secondsDiff + ' sec'
}

Context

StackExchange Code Review Q#152681, answer score: 3

Revisions (0)

No revisions yet.