xpageslotus-noteshcl-notes

(XPages)How can I write the code for calculate the number of days between dates?


I have a field name, called "REF_DATE". The "REF_DATE"'s format is "YYYY/MM/DD".

I need to calculate the number of days from today to the "REF_DATE".

For example:

REF_DATE = 2020/01/09

Today = 2020/04/01

The following is I tried the code:

var s1 = "2020/01/09";
var s2 = "2020/04/01";
var aDate = s1.split("/");
var oDate1 = Date.UTC(aDate[1],aDate[2],aDate[0]);
var bDate = s2.split("/");
var oDate2 = Date.UTC(bDate[1],bDate[2],bDate[0]);
var iDays = Math.floor((oDate2 - oDate1)/86400000);
return oDate1+"<br>"+oDate2+"<br>"+iDays+"<br>";

But the xpages showed "853".

So, I need you guys to help me with how to calculate the number of days between dates.

Thanks!!!!!!


Solution

  • Pass the year as the first Date.UTC parameter and subtract 1 from the month (0 is January):

    <?xml version="1.0" encoding="UTF-8"?>
    <xp:view xmlns:xp="http://www.ibm.com/xsp/core">    
    <xp:this.beforePageLoad><![CDATA[#{javascript:
        var s1 = "2020/01/09";
        var s2 = "2020/04/01";
        var aDate = s1.split("/");
        var oDate1 = Date.UTC(Number(aDate[0]), Number(aDate[1]-1), Number(aDate[2]));
    
        var aDate = s2.split("/");
        var oDate2 = Date.UTC(Number(aDate[0]), Number(aDate[1]-1), Number(aDate[2]));
    
        var iDays = Math.floor((oDate2 - oDate1) /1000/60/60/24);
        print(iDays);
    }]]></xp:this.beforePageLoad>
    </xp:view>