Javascript:获取前一周的周一和周日

use*_*577 6 javascript

我使用以下脚本获取前一周的周一(第一个)和周日(最后一个):

var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay() - 6; // Gets day of the month (e.g. 21) - the day of the week (e.g. wednesday = 3) = Sunday (18th) - 6
var last = first + 6; // last day is the first day + 6
var startDate = new Date(curr.setDate(first));
var endDate = new Date(curr.setDate(last));
Run Code Online (Sandbox Code Playgroud)

如果上个星期一和星期天也在同一个月,这个工作正常,但我今天才注意到,如果今天是12月,而上个星期一是11月,它就不起作用.

我是JS的新手,还有另外一种方法可以获得这些日期吗?

Rob*_*obG 14

您可以通过获取本周一的周一并减去7天来获得上周一.周日将是前一天,所以:

var d = new Date();

// set to Monday of this week
d.setDate(d.getDate() - (d.getDay() + 6) % 7);

// set to previous Monday
d.setDate(d.getDate() - 7);

// create new date of day before
var sunday = new Date(d.getFullYear(), d.getMonth(), d.getDate() - 1);
Run Code Online (Sandbox Code Playgroud)

对于2012-12-03我得到:

Mon 26 Nov 2012
Sun 25 Nov 2012
Run Code Online (Sandbox Code Playgroud)

那是你要的吗?

// Or new date for the following Sunday
var sunday = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 6);
Run Code Online (Sandbox Code Playgroud)

这使

Sun 02 Dec 2012
Run Code Online (Sandbox Code Playgroud)

通常,您可以通过添加和减去年,月和日来操纵日期对象.对象将自动处理负值,例如

var d = new Date(2012,11,0)
Run Code Online (Sandbox Code Playgroud)

将创建2012-11-30的日期(注意月份为零,因此11月是12月).也:

d.setMonth(d.getMonth() - 1); // 2012-10-30

d.setDate(d.getDate() - 30);  // 2012-09-30
Run Code Online (Sandbox Code Playgroud)


her*_*w78 7

如果您不想使用外部库,则应使用时间戳.我创建了一个解决方案,您可以从当前日期减去60*60*24*7*1000(即604800000,即1周毫秒)并从那里开始:

var beforeOneWeek = new Date(new Date().getTime() - 60 * 60 * 24 * 7 * 1000)
  , day = beforeOneWeek.getDay()
  , diffToMonday = beforeOneWeek.getDate() - day + (day === 0 ? -6 : 1)
  , lastMonday = new Date(beforeOneWeek.setDate(diffToMonday))
  , lastSunday = new Date(beforeOneWeek.setDate(diffToMonday + 6));
Run Code Online (Sandbox Code Playgroud)

  • 在使用DST的国家/地区不起作用,因为一周并不总是60*60*24*7*1000ms.例如,在法国的2014-03-31 00:30:00,即使3月24日和3月31日是星期一,lastMonday也将是2014-03-17. (3认同)