javascript 获取最近发生的星期日

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12791378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:07:56  来源:igfitidea点击:

Get the most recently occurring Sunday

javascriptdatedatetime

提问by Andrew Shepherd

I need to display the current week in a calendar view, starting from Sunday.

我需要在日历视图中显示当前周,从星期日开始。

What's the safest way to determine "last sunday" in Javascript?

在 Javascript 中确定“最后一个星期天”的最安全方法是什么?

I was calculating it using the following code:

我正在使用以下代码计算它:

Date.prototype.addDays = function(n) {
      return new Date(this.getTime() + (24*60*60*1000)*n);
}

var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var lastSunday = today.addDays(0-today.getDay());

This code makes the assumption that every day consists of twenty four hours. This is correct, EXCEPT if it's a daylight savings crossover day, in which case the day could be twenty-three or twenty-five hours.

此代码假设每天有二十四小时。这是正确的,除非是夏令时交叉日,在这种情况下,一天可能是二十三小时或二十五小时。

This week, In Sydney, Australia, we set our clocks forward an hour. As a result, my code calculates lastSundayas 23:00 on Saturday.

本周,在澳大利亚悉尼,我们将时钟拨快了一个小时。结果,我的代码计算lastSunday为星期六 23:00。

So what IS the safest and most efficient way to determine last Sunday?

那么确定上周日最安全、最有效的方法是什么?

回答by RobG

To safely add exactly one day, use:

要安全地添加一天,请使用:

d.setDate(d.getDate() + 1);

which is daylight saving safe. To set a date object to the last Sunday:

这是夏令时安全。要将日期对象设置为最后一个星期日:

function setToLastSunday(d) {
  return d.setDate(d.getDate() - d.getDay());
}

Or to return a new Date object for last Sunday:

或者为上周日返回一个新的 Date 对象:

function getLastSunday(d) {
  var t = new Date(d);
  t.setDate(t.getDate() - t.getDay());
  return t;
}

Edit

编辑

The original answer had an incorrect version adding time, that does add one day but not how the OP wants.

原始答案的版本添加时间不正确,这确实增加了一天,但不是 OP 想要的。

回答by rlay3

Try this jsfiddle

试试这个jsfiddle

It uses only built in date methods

它只使用内置的日期方法

var now = new Date();
var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var lastSunday = new Date(today.setDate(today.getDate()-today.getDay()));