我正在使用以下脚本获取前一周的星期一(第一个)和星期日(最后一个):
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));
如果上周一和周日也在同一个月,这很好用,但我今天才注意到,如果今天是 12 月而上周一是 11 月,它就不起作用。
我是一个 JS 新手,还有其他方法可以获取这些日期吗?
原文由 user18577 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果你不想用外部库来做,你应该使用时间戳。我创建了一个解决方案,您可以从当前日期减去 60*60*24*7*1000(即 604800000,以毫秒为单位为 1 周),然后从那里开始: