Get the difference between two dates with Javascript

This is nothing earthshaking; in fact, it’s almost a complete rip off of another blog post, where I initially found what I needed. But I thought I’d put it here, so it would be easier for me to find it again when I need it again:-)

function daysDiff(dayStart, daySubtract)

//if either date is empty, return empty string
if ((dayStart == ”||dayStart == null)||(daySubtract == ”||daySubtract == null)){
return ”;
else {
//convert values to dates
var dateStart = new Date(dayStart);
var dateSubtract = new Date(daySubtract);

//correct for 2-digit year entry
var dateStart = correctYear(dateStart);
var dateSubtract = correctYear(dateSubtract);

//one day in milliseconds
var oneDay=1000*60*60*24;

//use the getTime() method of the javascript date object, which converts
//date to milliseconds. Subtract dates, then divide by oneDay variable
//to convert milliseconds to days. Round using the Math.round()* method.
var days = Math.round((dateStart.getTime()-dateSubtract.getTime())/(oneDay));

//return variable
return days;

*Originally, I used Math.ceil() here (because the blog I ripped off used Math.ceil).  However, I found in practice that Math.ceil did not give me the results I wanted.  Math.ceil always rounds upwards to the nearest integer, whereas Math.round will round up or down to the nearest integer.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s