Created
March 29, 2011 11:24
-
-
Save dolmen/892185 to your computer and use it in GitHub Desktop.
StackOverflow #4829003: date diff testsuite
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See http://stackoverflow.com/questions/4829003/using-date-in-js-to-calculate-the-difference-between-two-dates-what-am-i-doin | |
// jQuery mock object for calculateTime | |
// $('#time').html(result) => result is stored in $.result | |
var $ = (function() { | |
var $, $$ = { | |
html: function(result) { | |
$.result = result | |
} | |
} | |
return $ = function(ignore) { | |
return $$ | |
} | |
})(); | |
function calculateTime(todaysDate,futureDate) { | |
var difference = futureDate.getTime() - todaysDate.getTime(); | |
var years = Math.floor(difference/1000/60/60/24/365); | |
difference -= years*1000*60*60*24*365; | |
var days = Math.floor(difference/1000/60/60/24); | |
difference -= days*1000*60*60*24; | |
var hours = Math.floor(difference/1000/60/60); | |
difference -= hours*1000*60*60; | |
var minutes = Math.floor(difference/1000/60); | |
difference -= minutes*60*1000; | |
var seconds = Math.floor(difference/1000); | |
var result = years + ' Years, '; | |
result += days + ' Days, '; | |
result += hours + ' Hours, '; | |
result += minutes + ' Minutes, '; | |
result += seconds + ' Seconds'; | |
return $('#time').html(result) | |
} | |
function test(a, b, expected) { | |
var toString = Object.prototype.toString; | |
if (toString.apply(a) != '[object Date]') a = new Date(a); | |
if (toString.apply(b) != '[object Date]') b = new Date(b); | |
calculateTime(a, b); | |
var got = $.result; | |
WScript.Echo( | |
got === expected | |
? "ok" | |
: "not ok - ["+a.toString()+"] to ["+b.toString()+"]\r\n# Got: "+got+"\r\n# Expected: "+expected | |
); | |
} | |
test('2010/11/24 23:00:00', '2011/11/24 23:00:00', '1 Years, 0 Days, 0 Hours, 0 Minutes, 0 Seconds'); | |
test('Nov 24, 2010 23:00:00', 'Nov 24, 2011 23:00:00', '1 Years, 0 Days, 0 Hours, 0 Minutes, 0 Seconds'); | |
test('2010/11/24 23:00:00', '2020/11/24 22:59:00', '10 Years, 0 Days, 0 Hours, 0 Minutes, 0 Seconds'); | |
test('2011/03/26 23:00:00', '2011/03/27 23:00:00', '0 Years, 1 Days, 0 Hours, 0 Minutes, 0 Seconds'); | |
test('2010/10/30 23:00:00', '2010/10/31 23:00:00', '0 Years, 1 Days, 0 Hours, 0 Minutes, 0 Seconds'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment