How do I get the number of days between two dates in JavaScript?
How do I get the number of days between two dates in JavaScript? For example, given two dates in input boxes:
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>
<script>
alert(datediff("day", first, second)); // what goes here?
</script>
Here is a quick and dirty implementation of datediff
, as a proof of concept to solve the problem as presented in the question. It relies on the fact that you can get the elapsed milliseconds between two dates by subtracting them, which coerces them into their primitive number value (milliseconds since the start of 1970).
// new Date("dateString") is browser-dependent and discouraged, so we'll write
// a simple parse function for U.S. date format (which does no error checking)
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function datediff(first, second) {
// Take the difference between the dates and divide by milliseconds per day.
// Round to nearest whole number to deal with DST.
return Math.round((second-first)/(1000*60*60*24));
}
alert(datediff(parseDate(first.value), parseDate(second.value)));
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>
The easiest way to get the difference between two dates:
var diff = Math.floor(( Date.parse(str2) - Date.parse(str1) ) / 86400000);
You get the difference days (or NaN if one or both could not be parsed). The parse date gived the result in milliseconds and to get it by day you have to divided it by 24 * 60 * 60 * 1000
If you want it divided by days, hours, minutes, seconds and milliseconds:
function dateDiff( str1, str2 ) {
var diff = Date.parse( str2 ) - Date.parse( str1 );
return isNaN( diff ) ? NaN : {
diff : diff,
ms : Math.floor( diff % 1000 ),
s : Math.floor( diff / 1000 % 60 ),
m : Math.floor( diff / 60000 % 60 ),
h : Math.floor( diff / 3600000 % 24 ),
d : Math.floor( diff / 86400000 )
};
}
Here is my refactored version of James version:
function mydiff(date1,date2,interval) {
var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
date1 = new Date(date1);
date2 = new Date(date2);
var timediff = date2 - date1;
if (isNaN(timediff)) return NaN;
switch (interval) {
case "years": return date2.getFullYear() - date1.getFullYear();
case "months": return (
( date2.getFullYear() * 12 + date2.getMonth() )
-
( date1.getFullYear() * 12 + date1.getMonth() )
);
case "weeks" : return Math.floor(timediff / week);
case "days" : return Math.floor(timediff / day);
case "hours" : return Math.floor(timediff / hour);
case "minutes": return Math.floor(timediff / minute);
case "seconds": return Math.floor(timediff / second);
default: return undefined;
}
}
链接地址: http://www.djcxy.com/p/36708.html
上一篇: 如何计算两个日期之间的天数?