Monday, July 15, 2013

To find day, month, week and year difference between two dates using jquery

<script>
function getDateDiff(date1, date2, interval) {
    var second = 1000,
    minute = second * 60,
    hour = minute * 60,
    day = hour * 24,
    week = day * 7;
    dateone = new Date(date1).getTime();
    datetwo = (date2) ? new Date().getTime() : new Date(date2).getTime();
    var timediff = datetwo - dateone;
secdate = new Date(date2);
firdate = new Date(date1);
    if (isNaN(timediff)) return NaN;
    switch (interval) {
    case "years":
        return secdate.getFullYear() - firdate.getFullYear();
    case "months":
        return ((secdate.getFullYear() * 12 + secdate.getMonth()) - (firdate.getFullYear() * 12 + firdate.getMonth()));
    case "weeks":
        return Math.floor(timediff / week);
    case "days":
        return Math.floor(timediff / day);
    case "hours":
        return Math.floor(timediff / hour);
    case "minutes":
        return Math.floor(timediff / minute);
    case "seconds":
        return Math.floor(timediff / second);
    default:
        return undefined;
    }
}

getDateDiff('1948/11/12', new Date(), 'months');

first parameter should be the date from where you want to know the diff.

second parameter should be the present date or whatever you wish

Third parameter should be the type of diff that you want between the two dates. (ex. years, months, weeks, days, hours, minutes, seconds)

</script>

No comments:

Post a Comment