Count Number Of Days Between 2 Dates In Javascript
Solution 1:
Use
var firstDate = newDate(); // Todays datevar secondDate = newDate(2011,08,19, 11,49,01);
var diffDays = (firstDate.getDate() - secondDate.getDate());
It was showing NAN as your constructor is wrong. check yourself by alerting secondDate in your original code
Edit : above code will work if both dates are in same month, for general case
var oneDay = 24*60*60*1000;
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime()) / oneDay);
Also this will give result as fraction of date, so if you want to count whole dates you can use Math.ceil or Math.floor
Solution 2:
Use this:
var udate="2011-08-19 11:49:01.0 GMT+0530";
The IST part is not valid
Solution 3:
your input date is incorrect that is why it is failing. anyways here is some code that should help you with it.
varDateDiff = {
inDays: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
returnparseInt((t2-t1)/(24*3600*1000));
},
inWeeks: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
returnparseInt((t2-t1)/(24*3600*1000*7));
},
inMonths: function(d1, d2) {
var d1Y = d1.getFullYear();
var d2Y = d2.getFullYear();
var d1M = d1.getMonth();
var d2M = d2.getMonth();
return (d2M+12*d2Y)-(d1M+12*d1Y);
},
inYears: function(d1, d2) {
return d2.getFullYear()-d1.getFullYear();
}
}
var udate="2011-08-05 11:49:01";
var configDate=newDate(udate);
var oneDay = 24*60*60*1000; // hours*minutes*seconds*millisecondsvar firstDate = newDate(); // Todays datevar secondDate = newDate(udate);
alert(secondDate);
var diffDays = DateDiff .inDays(firstDate,secondDate);
alert(diffDays );
Solution 4:
if you have udate
format like 28-07-2011
you can use this
var checkindatestr = "28-07-2011";
var dateParts = checkindatestr.split("-");
var checkindate = newDate(dateParts[2], dateParts[1] - 1, dateParts[0]);
var now = newDate();
var difference = now - checkindate;
var days = difference / (1000*60*60*24);
alert(days);
Solution 5:
You are calculating the difference correctly but the problem is that secondDate
is an invalid date. Date
cannot work with that date format, it needs "August 08, 2011 11:49:01"
as input - and if your date has a different format then you have to convert it. Note that Date
has only rudimentary timezone recognition, you can only be sure that "UTC" or "GMT" will be recognized correctly - you shouldn't use other time zones.
Post a Comment for "Count Number Of Days Between 2 Dates In Javascript"