Posted By

camdagr8 on 11/20/13


Tagged

javascript date


Versions (?)

Date.lapsed(Date)


 / Published in: JavaScript
 

Calculates the time in hh:mm:ss between two dates

Usage: var past = new Date('1/1/2013'); var now = new Date();

var lapsed = past.lapsed(now);

  1. Date.prototype.lapsed = function (now) {
  2. now = now || new Date();
  3.  
  4. var milliseconds = Math.abs(this.getTime() - now.getTime());
  5.  
  6. var oneHour = 3600000;
  7. var oneMinute = 60000;
  8. var oneSecond = 1000;
  9. var hours = 0;
  10. var minutes = 0;
  11. var result;
  12. var seconds = 0;
  13.  
  14. if (milliseconds >= oneHour) { hours = Math.floor(milliseconds / oneHour); }
  15.  
  16. milliseconds = hours > 0 ? (milliseconds - hours * oneHour) : milliseconds;
  17.  
  18. if (milliseconds >= oneMinute) { minutes = Math.floor(milliseconds / oneMinute); }
  19.  
  20. milliseconds = minutes > 0 ? (milliseconds - minutes * oneMinute) : milliseconds;
  21.  
  22. if (milliseconds >= oneSecond) { seconds = Math.floor(milliseconds / oneSecond); }
  23.  
  24. milliseconds = seconds > 0 ? (milliseconds - seconds * oneSecond) : milliseconds;
  25.  
  26. if (hours > 0) { result = (hours > 9 ? hours : "0" + hours) + ":"; }
  27. else { result = "00:"; }
  28.  
  29. if (minutes > 0) { result += (minutes > 9 ? minutes : "0" + minutes) + ":"; }
  30. else { result += "00:"; }
  31.  
  32. if (seconds > 0) { result += (seconds > 9 ? seconds : "0" + seconds); }
  33. else { result += "00"; }
  34.  
  35. return result;
  36. };

Report this snippet  

You need to login to post a comment.