Hi,
I want to calculate the number of days between two dates.
Date is in the below format:
First Date : 2010-09-27 05:00:00
Second Date : 2010-10-1 08:00:00
Thanks.
Hi,
I want to calculate the number of days between two dates.
Date is in the below format:
First Date : 2010-09-27 05:00:00
Second Date : 2010-10-1 08:00:00
Thanks.
Good starting answers from (millisecond subtraction) and (string parsing + helper methods). Two important pitfalls to watch before you pick an implementation: string parsing is inconsistent across engines, and “days” can mean different things (calendar days vs exact 24‑hour periods) when you cross daylight‑saving or time‑zone boundaries. (developer.mozilla.org)
Parsing: the input strings in the original post (e.g. 2010-09-27 05:00:00 and 2010-10-1 08:00:00) are not guaranteed to be interpreted the same way by new Date(string) in every environment. Prefer a strict ISO form (use T between date and time, zero‑pad components, and include a zone or Z if you mean UTC), or parse the components yourself and construct the Date with numeric arguments. For modern code, consider the new Temporal API or a proven date library so you avoid hand‑rolled parsing. (developer.mozilla.org)
Counting days correctly: decide whether you want "full 24‑hour periods" or "calendar‑day differences." If you want calendar days regardless of DST, normalize both dates to midnight (UTC or local, consistently) and subtract those normalized timestamps; if you want exact 24‑hour blocks, subtract timestamps directly and divide by the milliseconds-per-day value. Be aware that libraries like date‑fns document that a “full day” is measured in local time and that DST can make a day shorter/longer. (developer.mozilla.org)
Practical recommendation: for one-off scripts, parse components and use Date.UTC(...) (or construct with numeric args) then compute differences; for production work use Temporal or a maintained library (date‑fns, Luxon) which handles parsing, zones and DST semantics explicitly so you don’t get subtle off‑by‑one results. Decide up front whether partial days should round up, down, or be truncated—this determines whether you use floor/ceil/round. (developer.mozilla.org)
Jump to Post— Protuberance 67//Set the two dates today=new Date() var christmas=new Date(today.getFullYear(), 11, 25) //Month is 0-11 in JavaScript if (today.getMonth()==11 && today.getDate()>25) //if Christmas has passed already christmas.setFullYear(christmas.getFullYear()+1) //calculate next year's Christmas //Set 1 day in milliseconds var one_day=1000*60*60*24 //Calculate difference btw the two dates, and convert to days …
//Set the two dates
today=new Date()
var christmas=new Date(today.getFullYear(), 11, 25) //Month is 0-11 in JavaScript
if (today.getMonth()==11 && today.getDate()>25) //if Christmas has passed already
christmas.setFullYear(christmas.getFullYear()+1) //calculate next year's Christmas
//Set 1 day in milliseconds
var one_day=1000*60*60*24
//Calculate difference btw the two dates, and convert to days
document.write(Math.ceil((christmas.getTime()-today.getTime())/(one_day))+
" days left until Christmas!") Solution from
P.S. try to google it.
Techie,
First extend Date to add a setDateTime method, which accepts a string of the necessary format :
Date.prototype.setDateTime = function(dt, ignoreTime) {
try {
ignoreTime = (!ignoreTime) ? false : true;
dt = dt.replace(/\s+/g, ' ').replace(/^\s/, '').replace(/\s$/, '');//reduce multiple spaces to single space, then purge any leading and trailing spaces
var parts = dt.split(' ');
var d = parts[0].split('-');
if(d.length >= 1) { this.setYear(d[0]); }
if(d.length >= 2) { this.setMonth(d[1]-1); }
if(d.length >= 3) { this.setDate(d[2]); }
var t = (ignoreTime || parts.length < 2) ? [0,0,0] : parts[1].split(':');
if(t.length >= 1) { this.setHours(t[0]); }
if(t.length >= 2) { this.setMinutes(t[1]); }
if(t.length >= 3) { this.setSeconds(t[2]); }
return this.getTime();
}
catch(e) { return false; }
}; This includes a measure of inbuilt safety to help guard against an error should an incomplete string, or a string of the wrong format, be passed to it.
Now you can use this method as follows :
var d1 = new Date();
var d2 = new Date();
var first_Date = '2010-09-27 05:00:00';
var second_Date = '2010-10-1 08:00:00';
d1.setDateTime(first_Date, false);
d2.setDateTime(second_Date, false); Depending on exactly what you are trying to do, you may choose to set the second parameter to true, which would cause the hh:mm:ss part of the dateTime to be ignored (effectively setting the time to midnight).
To calculate the difference between two Dates, we add a second method to the Date prototype:
Date.prototype.subtract = function(d, returnAs) {
returnAs = (!returnAs) ? '' : returnAs;
switch(returnAs) {
case 'days':
return (this-d)/(24*60*60*1000);
break;
case 'hours':
return (this-d)/(60*60*1000);
break;
case 'minutes':
return (this-d)/(60*1000);
break;
case 'seconds':
return (this-d)/1000;
break;
default://milliseconds
return this-d;
}
} Call as follows:
var days = d2.subtract(d1, 'days'); The result is a floating point number, which you can use raw or as Math.floor(days) , Math.ceil(days) or Math.round(days) as appropriate to your application.
This gives some reusable code with a degree of flexibility.
Airshow
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.