/ 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);
Usage:
var past = new Date('1/1/2013');
var now = new Date();
var lapsed = past.lapsed(now);
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
Date.prototype.lapsed = function (now) { now = now || new Date(); var milliseconds = Math.abs(this.getTime() - now.getTime()); var oneHour = 3600000; var oneMinute = 60000; var oneSecond = 1000; var hours = 0; var minutes = 0; var result; var seconds = 0; if (milliseconds >= oneHour) { hours = Math.floor(milliseconds / oneHour); } milliseconds = hours > 0 ? (milliseconds - hours * oneHour) : milliseconds; if (milliseconds >= oneMinute) { minutes = Math.floor(milliseconds / oneMinute); } milliseconds = minutes > 0 ? (milliseconds - minutes * oneMinute) : milliseconds; if (milliseconds >= oneSecond) { seconds = Math.floor(milliseconds / oneSecond); } milliseconds = seconds > 0 ? (milliseconds - seconds * oneSecond) : milliseconds; if (hours > 0) { result = (hours > 9 ? hours : "0" + hours) + ":"; } else { result = "00:"; } if (minutes > 0) { result += (minutes > 9 ? minutes : "0" + minutes) + ":"; } else { result += "00:"; } if (seconds > 0) { result += (seconds > 9 ? seconds : "0" + seconds); } else { result += "00"; } return result; };