如何在javascript中获得下周的约会

Jin*_*ong 26 javascript

有谁知道如何根据本周日期获得下周的日期?例如,如果我有这个星期四的日期(25/6/2009),我如何使用javascript来获得下一个星期四的日期(2009年2月7日)?

Mat*_*hen 56

var firstDay = new Date("2009/06/25");
var nextWeek = new Date(firstDay.getTime() + 7 * 24 * 60 * 60 * 1000);
Run Code Online (Sandbox Code Playgroud)

如果您喜欢"流利的"API,也可以查看DateJS.

  • 但是,在DST更改的一周内不起作用:( (3认同)

glm*_*ndr 35

function nextweek(){
    var today = new Date();
    var nextweek = new Date(today.getFullYear(), today.getMonth(), today.getDate()+7);
    return nextweek;
}
Run Code Online (Sandbox Code Playgroud)

  • 但是,这可能会生成一些无效的日期,这些日期可能有效也可能无效,这取决于目标JS引擎Date()函数的智能程度。例如,2013年8月30日之后的一周将是2013年8月37日,这是无效的。 (3认同)

Vol*_*ker 11

function dateObject.getNextWeekDay返回对象自己的日期之后的下一个工作日.

Date.prototype.getNextWeekDay = function(d) {
  if (d) {
    var next = this;
    next.setDate(this.getDate() - this.getDay() + 7 + d);
    return next;
  }
}

var now = new Date();
var nextMonday = now.getNextWeekDay(1); // 0 = Sunday, 1 = Monday, ...
var secondNextMonday = new Date(nextMonday).getNextWeekDay(1);
console.log('Next Monday : ' + nextMonday);
console.log('Second Next Monday : ' + secondNextMonday);
Run Code Online (Sandbox Code Playgroud)

  • 并污染日期原型 - 见 http://programmers.stackexchange.com/questions/104320/why-is-extending-the-dom-built-in-object-prototypes-a-bad-idea (2认同)

raz*_*zed 9

Date.prototype.addDays = function (d) {
    if (d) {
        var t = this.getTime();
        t = t + (d * 86400000);
        this.setTime(t);
    }
};

this_week.addDays(7);
Run Code Online (Sandbox Code Playgroud)

  • 你永远不知道你最终会使用哪个库.您可能会使用定义addDays方法的内容来计算工作日.然后你挠挠头. (3认同)
  • 不过,我会让日期原型单独存在。 (2认同)