Want to get the number of days between two dates in JavaScript? 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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // 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))); |
1 2 | <input id="first" value="1/1/2000"/> <input id="second" value="1/1/2001"/> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.