本文介绍了Javascript:获取前一周的周一和周日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the following script to get Monday (first) and Sunday (last) for the previous week:

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));

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

This works fine if last Monday and Sunday were also in the same month, but I just noticed today that it doesn't work if today is December and last Monday was in November.

我是JS的新手,还有其他方法可以获得这些日期吗?

I'm a total JS novice, is there another way to get these dates?

推荐答案

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

if you dont want to do it with an external library you should work with timestamps. i created a solution where you would substract 60*60*24*7*1000 (which is 604800000, which is 1 week in milliseconds) from the current Date and go from there:

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));

这篇关于Javascript:获取前一周的周一和周日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 23:52