简体   繁体   中英

javascript .setDate() wrong date output

I am trying to get new dates in a range from a starting date and an offset (number + unit), but .setDate is behaving incorrectly, both t.start and t.end in the code below are correct ISOStrings (created with the javascript function .toISOString()):

while(t.start < t.end) {
        console.log(t.start);
        t.start = new Date(t.start);
        console.log("original toDate "+t.start);
        //calculate the new start
        switch(unit) {
            case "giorno":
                console.log("adding days: " + n + " to " + t.start.getDate());
                t.start.setDate(t.start.getDate() + n);
                break;
            case "settimana":
                t.start.setDate(t.start.getDate() + n*7);
                break;
            case "mese":
                t.start = addMonths(t.start, n);
                break;
            case "anno":
                t.start.setFullYear(t.start.getFullYear() + n);
                break;
        }
        console.log("Post add: "+t.start);
        t.start  = t.start.toISOString();
    }

"giorno", "settimana", "mese", "anno" are the Italian counterparts to "day", "week", "month", "year" as you could guess from the code. Running this code on 2015-09-11T00:00:00.000Z with n=1, unit="giorno" and t.end = 2015-09-13T00:00:00.000Z returns this output:

2015-09-11T00:00:00.000Z
original toDate Fri Sep 11 2015 02:00:00 GMT+0200 (W. Europe Summer Time)
adding days: 1 to 11
Post add: Sun Dec 20 2015 02:00:00 GMT+0100 (W. Europe Standard Time)

First 3 console.log() are what I would expect. The last one should be Sat Sep 12 2015... and I cannot understand why it isn't (I also tried converting everything into moments with moment.js, same error)

When I place this code in front of your while loop, it works as expected:

t={}
t.start="2015-09-11T00:00:00.000Z"
t.end="2015-09-13T00:00:00.000Z"
unit="giorno"
n=1

However, when I replace the last line with

n="1"

I get the same result you did.

Since

console.log("1" + 11)

gives 111, it would appear that you are setting the date to 111 days after the start of September, which is December 20.

Perhaps you need to use n=parseInt(n) near the top so you are adding numbers instead of strings?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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