javascript日期对象丢失了它的类型

时间:2012-12-14 15:43:13

标签: javascript

对于以下代码,

$(function() {
    a = new Date("2008-1-2");

    monthDiff = function(now, then) {
        var months;
        months = (now.getFullYear() - then.getFullYear()) * 12;
        months -= then.getMonth() + 1;
        months += now.getMonth();
        return months;
    };

    intervalToDate = function(interval, start, unit) {
        {
            return {
                day: function() {return new Date(start.getTime() + (interval*24*60*60*1000)); },
                week: function() {return new Date(start.getTime() + (interval*7*24*60*60*1000)); },
                month: function() {
                    // the result value below will not return a date object when running (only an object), what is weird is in the debug console, using the line below will totally return a date object.
                    var result = new Date(start.getTime() + interval*4*7*24*60*60*1000);
                    while (monthDiff(result, start) !== interval) {
                        result += 24*60*60*1000;
                    }
                    return result;
                } ,
                year: function() {
                    return start.getFullYear() + interval;
                }
            }[unit]();
        }
    };

    console.log(intervalToDate(20, a, "day"));
    console.log(intervalToDate(20, a, "week"));
    console.log(intervalToDate(20, a, "month"));
    console.log(intervalToDate(20, a, "year"));
})

这一行:

month: function() {
                        // the result value below will not return a date object when running (only an object), what is weird is in the debug console, using the line below will totally return a date object.
                        var result = new Date(start.getTime() + interval*4*7*24*60*60*1000);

结果将在调试控制台中正确返回。但是在运行时,它不再是一个日期对象,所以当我尝试在其上调用getFullYear函数时,我遇到了“无方法错误”。

2 个答案:

答案 0 :(得分:2)

你是日期对象的加法和整数值result += 24*60*60*1000;,你必须使用日期方法来增加时间,而不仅仅是做一个简单的加法。

示例:

result.setMilliseconds(result.getMilliseconds() + (24*60*60*1000));

答案 1 :(得分:0)

怎么样...... ...

while (monthDiff(result, start) !== interval) {
    result = new Date(result.getTime() + 24*60*60*1000);
}