简体   繁体   English

计算JavaScript和xml中的天数

[英]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. 我想计算自从在xml节点中输入值到当前日期的天数。 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. 为此,我尝试结合使用两个脚本,这些脚本在Firefox和Chrome中都可以正常运行-但在Explorer和Safari中效果不佳,而结果显示为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>

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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM