开发者

What's wrong with my implementation, using Date object's setDate function

I have a date object and I need to create another date object that is 1 week after the first date object. I already have an implementation but it seems that there is a bug with javascript when it reaches the months of October, November and December. Is there a workaround for this? Note that the behavior is consistent across Chrome, FF and IE.

        // ************ TEST#1 ************
        var startDate = new Date(2011,08,05); // set to Sept 5, 2011
        alert('START DATE' + startDate);

        var endDate = new Date();
        endDate.setDate(startDate.getDate() + 7);

        alert('END DATE' + endDate); // endDate is Sept 12 which is correct
        //开发者_开发问答 check that startDate's value is unchanged
        alert('START DATE' + startDate); 


        // ************ TEST#2 ************
        var startDate = new Date(2011,10,05); // set to Nov 5, 2011
        alert('START DATE' + startDate);

        var endDate = new Date();
        endDate.setDate(startDate.getDate() + 7);

        alert('END DATE' + endDate); // endDate is Sept 12, 2011 which is wrong
        alert('START DATE' + startDate);



        // ************ TEST#3 ************
        // changed implementation but this won't work
        var startDate = new Date(2011,10,05);
        alert('START DATE' + startDate);

        var endDate = startDate;
        endDate.setDate(startDate.getDate() + 7);

        alert('END DATE' + endDate); // endDate is correct but...
        alert('START DATE' + startDate); // startDate's value has changed as well


I think your error might be that you are setting endate to today.

    // ************ TEST#2 ************
    var startDate = new Date(2011,10,05); // set to Nov 5, 2011
    alert('START DATE' + startDate);

    // edit
    var endDate = new Date(startDate.getFullYear(),startDate.getMonth(),startDate.getDate() + 7);
    // old var endDate = new Date();
    // endDate.setDate(startDate.getDate() + 7);

    alert('END DATE' + endDate); // endDate is Sept 12, 2011 which is wrong
    alert('START DATE' + startDate);


This is not a bug. In this case Date is an object and both startDate and endDate refer to the same Date instance. Hence when you change the underlying object it's visible through both references

EDIT

OP specified the bug is in Test #2

This is still not a bug. The problem here is that setDate will only change the day of the month. In this you've executed startDate.getDate() + 7 where startDate.getDate() === 5 so it's correctly adjusting the date portion of endDate to the 12th of the month.


In addition to JaredPar, new Date() will create a date with current time, and if you only invoke .setDate() you will only change "day of month".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜