Javascript Days Between 2 Dates Return Wrong
Solution 1:
An algorithm to calculate the calendar date difference between two date in terms of years, months, days is as follows:
validate dates to have full years (4 digits), months in range 1-12, and month-day in range 1 - days in month of year of date.
subtract earlier date days from later date days. If borrow required, add days in the month of earlier date, in the year of the earlier date, to later date days and add 1 to months to be subtracted.
subtract earlier date month from later date months. If borrow required, add 12 to later day months and add 1 to years to be subtracted.
subtract earlier date year from later date year.
This may have been implemented in one existing answer to this question in a chain of duplicate questions, but try and spot it without documentation of the algorithm. The calculation of days to borrow can be calculated as follows:
function monthDays(y, m) // full year and month in range 1-12
{ var leap = 0;
if( m == 2)
{ if( y % 4 == 0) leap = 1;
if( y % 100 == 0) leap = 0;
if( y % 400 == 0) leap = 1;
}
return [0, 31,28,31,30,31,30,31,31,30,31,30,31][ m] + leap;
}
(Edit) or alternatively as per comment, using the behavior of Date objects adjusting to out of expected bound behavior:
function monthDays( y, m)
{ return new Date(y, m, 0).getDate();
}
Solution 2:
HTML
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>
<script>
alert(datediff("day", first, second)); // what goes here?
</script>
JavaScript
function parseDate(str) {
var mdy = str.split('/')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
Source: How do I get the number of days between two dates in JavaScript?
Solution 3:
function days_between(date1, date2) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms);
// Convert back to days and return
return Math.round(difference_ms / ONE_DAY);
}
Post a Comment for "Javascript Days Between 2 Dates Return Wrong"