Tuesday, August 18, 2009

Get difference between Dates in Java script

It is very simple and easy to implement the difference between two dates. I received some queries on how to do it. So, this is the post for them.

function parseDate(str) {
    var date = str.split('/');
    return new Date(date[2], date[0] - 1, date[1]);
}

function GetDaysBetweenDates(date1, date2) {
    return (date2 - date1) / (1000 * 60 * 60 * 24)
}

"parseDate" is the function which is for converting a string to Date object. And the method "GetDaysBetweenDates" is expecting two date parameters which calculate the difference between the dates and return the result in number of days. You can change the formula as you want to return in time, months, weeks etc…

Enjoy!!!

1 comment:

  1. Wow, I hadn't thought about it that way before. Good write up, very clearly written. Have you written previously about Get difference between Dates in Java script? I'd love to read more.

    ReplyDelete