setDate(day + 1)返回错误的日期

时间:2011-05-23 05:52:16

标签: javascript

为什么这样:

startDate.setDate(startDate + 1);

生成这个奇怪的顺序(在下个月初打破):

7, 27, 28, 30, 30, **1, 4, 3, 4, 4,** 6, 7, 10, 9, 10, 10, 12,

更新(更多代码):

renderWeekFromMonday : function(date) {
        var dayContainer = $('#day');

        // clear div
        dayContainer.empty();

        // Render days
        for (var i = 0; i <= 7; i++) {

            // Get mondday day (1-31)
            var day = date.getDate();

            // Today
            var t = new Date();

            // Create dayobject for usage inside for loop
            var d = new Date(date);

            // Render 7 days (1 week)
            for (var i = 0; i < 7; i++) {

                // New day (+1)
                d.setDate(day + i)
                console.info(d.getDate());

                // Create html
                var span = $("<span>").addClass("calElement").attr("time", d.getTime())
                var w = 25;
                span.html("<span class=dayNumber>" + d.getDate() + "</span><br>" + this.dayNames[d.getDay()]).css("width",w);
                //span.html("<span class=dayNumber>" + d.getDate() + "</span>");

                // Append day
                dayContainer.append(span);
            }
        }
    },

3 个答案:

答案 0 :(得分:3)

只是一个猜测,或许你正在寻找:

startDate.setDate(startDate.getDate() + 1);
如果startDate + 1startDate对象,则

Date没有多大意义。


看到更新后的代码:您的问题很可能是因为您有两个嵌套循环,两个循环都递增i。为其中一个循环使用不同的变量。

答案 1 :(得分:0)

您的代码看起来很好 - 我正在使用FF4并且日期计算看起来正确。我在这里发布了一个实例的代码:http://jsfiddle.net/EbNcr/2/

是否有您要测试的特定浏览器或日期以获得奇怪的结果?

(我希望我可以将此作为评论提交,但我认为我还没有这个名声......)

答案 2 :(得分:0)

感谢您的帮助。我只是有一个简单的复制和粘贴错误(两个循环)。我将最终的代码放入一个简单的jquery插件(由一些oder插件激发)

var MILLIS_IN_DAY = 86400000;
var MILLIS_IN_WEEK = MILLIS_IN_DAY * 7

jQuery.fn.calendarPicker = function(options) {

// --------------------------  start default option values --------------------------
options.date = new Date();
options.dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
options.firstDayOfWeek = 1;
options.showNavigation = true;

// --------------------------  end default option values --------------------------

var calendar = {

    changeDate : function(date) {
        // calculate new start date
        this.currentFirstDayOfWeek = this._firstDayOfWeek(date);

        // render days
        for (var i = 0; i < 7; i++) {
            // create dayobject
            var day = new Date(this.currentFirstDayOfWeek.getTime() + MILLIS_IN_DAY * i);

            // render container
            var span = $("<span>").addClass("calElement").attr("time", day.getTime())

            // render day
            span.html("<span class=dayNumber>" + day.getDate() + "</span><br>" + options.dayNames[day.getDay()]);

            if (day.getYear() == date.getYear() && date.getMonth() == day.getMonth() && day.getDate() == date.getDate())
                span.addClass("today");
            if (day.getYear() == date.getYear() && day.getMonth() == date.getMonth() && day.getDate() == date.getDate())
                span.addClass("selected");
            theDiv.append(span);

            // render navigation
            if (i == 0 && options.showNavigation) {
                var prevBtn = $("<span>").addClass("prev").html("prev");
                var self = this;
                prevBtn.bind('click', function() { self.prevWeek(); });
                theDiv.prepend(prevBtn);
            } else if (i == 6 && options.showNavigation) {
                var nextBtn = $("<span>").addClass("next").html("next")
                var self = this;
                nextBtn.bind('click', function() { self.nextWeek(); });
                theDiv.append(nextBtn);
            }
        }
    },
    /*
     * Go to the previous week relative to the currently displayed week
     */
    prevWeek : function() {
        //minus more than 1 day to be sure we're in previous week - account for daylight savings or other anomolies
        var newDate = new Date(this.currentFirstDayOfWeek.getTime() - (MILLIS_IN_WEEK / 6));
        this._clearCalendar();
        this.changeDate(newDate);
    },
    /*
     * Go to the next week relative to the currently displayed week
     */
    nextWeek : function() {
        //add 8 days to be sure of being in prev week - allows for daylight savings or other anomolies
        var newDate = new Date(this.currentFirstDayOfWeek.getTime() + MILLIS_IN_WEEK + (MILLIS_IN_WEEK / 7));
        this._clearCalendar();
        this.changeDate(newDate);
    },
    /*
     * returns the date on the first millisecond of the week
     */
    _firstDayOfWeek : function(date) {
        var midnightCurrentDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
        var adjustedDate = new Date(midnightCurrentDate);
        adjustedDate.setDate(adjustedDate.getDate() - this._getAdjustedDayIndex(midnightCurrentDate));

        return adjustedDate;
    },
    _clearCalendar : function() {
        theDiv.empty();
    },
    /*
     * gets the index of the current day adjusted based on options (e.g.firstDayofWeek)
     */
    _getAdjustedDayIndex : function(date) {

        var midnightCurrentDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
        var currentDayOfStandardWeek = midnightCurrentDate.getDay();
        var days = [0,1,2,3,4,5,6];
        this._rotate(days, this.options.firstDayOfWeek);

        return days[currentDayOfStandardWeek];
    },
    /*
     * rotate an array by specified number of places.
     */
    _rotate : function(a, p ) {
        for (var l = a.length, p = (Math.abs(p) >= l && (p %= l),p < 0 && (p += l),p), i, x; p; p = (Math.ceil(l / p) - 1) * p - l + (l = p)) {
            for (i = l; i > p; x = a[--i],a[i] = a[i - p],a[i - p] = x);
        }
        return a;
    },
};

// Pass options
calendar.options = options;

// build the calendar on the first element in the set of matched elements.
var theDiv = this.eq(0);//$(this);
theDiv.addClass("calBox");

// empty the div
theDiv.empty();

// entry point
calendar.changeDate(options.date);

return calendar;

};