Thursday 15 March 2012

Difference betwen two dates in JavaScript

// LM is the number of days in one year = 365.25/12 days
var ds, aux, D0, D1, DD, DM, DY, LM = 30.4375;

// The returned format date is dd-mm-yy
// JavaScript Date object uses yy-mm-dd
ds = getValue("CrmForm_contract_sdate");
var aux = ds.split("-");
ds = aux[2] + "-" + aux[1] + "-" + aux[0];
D0 = new Date(ds.replace(/\D+/g, "/"));

ds = getValue("Calculator_contract_edate");
aux = ds.split("-");
ds = aux[2] + "-" + aux[1] + "-" + aux[0];
D1 = new Date(ds.replace(/\D+/g, "/"));

// D0 and D1 have the representation of the Date in miliseconds
// Now a day has 24*60*60*1000 miliseconds
DD = Math.round((D1 - D0) / 86400000);
DM = DD / LM | 0;
DD = Math.round(DD - DM * LM);
DY = DM / 12 | 0;
DM %= 12;

aux = DY + "Year";
if (DY>1 || DY==0)
    aux += "s, ";
else
    aux += ", ";
aux += DM + "Month";
if (DM>1 || DM==0)
    aux += "s, ";
else
    aux += ", ";
aux += DD + "Day";
if (DD>1 || DD==0)
    aux += "s, ";
else
    aux += ", ";

$("#lnyears").html("<font color=\"red\" size=\"3\">" + aux + "</font>");