McClaudLive
McClaudLive

Reputation: 53

Calculate number of days in JavaScript and xml

I would like to calculate the number of days since the value entered in a xml node and up to present day. I have tried to combine two scripts for this purpose which works fine in both Firefox and Chrome - but not in Explorer and Safari where the result is displayed as NaN. Please see the script below. Thank you in advance.


<div>
    <script type="text/javascript">
    function loadXMLDoc(dname)
    {
    (window.XMLHttpRequest)
    {
    xhttp=new XMLHttpRequest();
    }
    xhttp.open("GET",dname,false);
    xhttp.send();
    return xhttp.responseXML;
    }
    xmlDoc=loadXMLDoc("date.xml?v="+Math.floor((Math.random()*5000)+1).toString());
    x=xmlDoc.getElementsByTagName("ABC")[0]
    y=x.childNodes[0];

    var startDate = new Date(y.nodeValue);
    var endDate =  new Date();
    function diffDays(d1, d2)
    {
    var ndays;
    var tv1 = d1.valueOf();
    var tv2 = d2.valueOf();
    ndays = (tv2 - tv1) / 1000 / 86400;
    ndays = Math.round(ndays - 0.5);
    return ndays;
    }
</script>

Upvotes: 0

Views: 60

Answers (1)

Dibran
Dibran

Reputation: 1555

Ill suggest you use moment as a date/time library. Its the best library for this kind of code.

var currDate = moment():
var givenDate = moment(y.nodeValue);
return givenDate.diff(currentDate, 'days');

Upvotes: 1

Related Questions