﻿function isDate(sDate) {
    if (sDate != null) {
        var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
        if (re.test(sDate)) {
            var dArr = sDate.split("/");
            var d = new Date(dArr[2] + "/" + dArr[1] + "/" + dArr[0]);
            return d.getMonth() + 1 == dArr[1] && d.getDate() == dArr[0] && d.getFullYear() == dArr[2];
        }
        else {
            return false;
        }
    }
}

function dateDiff(sDateA, sDateB) {
    if (isDate(sDateA) && isDate(sDateB)) {
        nDaysDiff = 0;

        var strYearA = sDateA.substr(6, 4);
        var strMonthA = sDateA.substr(3, 2);
        var strDayA = sDateA.substr(0, 2);
        var dDateA = new Date(parseInt(strYearA), Number(strMonthA) - 1, Number(strDayA));


        var strYearB = sDateB.substr(6, 4);
        var strMonthB = sDateB.substr(3, 2);
        var strDayB = sDateB.substr(0, 2);
        var dDateB = new Date(parseInt(strYearB), Number(strMonthB) - 1, Number(strDayB));


        var dDifference = dDateB - dDateA;
        var nDaysDiff = Math.round(dDifference / (1000 * 60 * 60 * 24));
        return nDaysDiff;
    } else return (-9999);
}


//ritorna il numero di giorni trascorsi da una data alla stessa data dopo che sono trascorsi "years" anni
//questo perche' il calcolarla con 365*n_anni non tiene conto degli anni bisestili
function age(sBirthDate, years) {
    if (isDate(sBirthDate) && !isNaN(years)) {
        nDaysDiff = 0;

        var strYearA = sBirthDate.substr(6, 4);
        var strMonthA = sBirthDate.substr(3, 2);
        var strDayA = sBirthDate.substr(0, 2);
        var dDateA = new Date(parseInt(strYearA), Number(strMonthA) - 1, Number(strDayA));


        var strYearB = parseInt(strYearA,10) + parseInt(years,10);
        var strMonthB = strMonthA;
        var strDayB = strDayA;
        var dDateB = new Date(parseInt(strYearB), Number(strMonthB) - 1, Number(strDayB));


        var dDifference = dDateB - dDateA;
        var nDaysDiff = Math.round(dDifference / (1000 * 60 * 60 * 24));
        return nDaysDiff;
    } else return (-9999);
}

