得到最近发生的星期天 [英] Get the most recently occurring Sunday
问题描述
在Javascript中确定最后一个星期几最安全的方法是什么?
>我使用以下代码计算:
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());
此代码假设每天都包含二十四小时。这是正确的,除非是夏令时间的交叉日,在这种情况下,这天可能是二十三或二十五小时。
本周,在悉尼,澳大利亚,我们把时钟摆到了一个小时。因此,我的代码在星期六计算 lastSunday
为23:00。
那么什么是最安全和最多确定上个星期天的高效方法?
要安全添加一天,请使用:
d.setDate(d.getDate()+ 1);
这是夏令时的安全。要将日期对象设置为上一个星期天:
函数setToLastSunday(d){
return d.setDate .getDate() - d.getDay());
}
或返回上一个星期天的新Date对象:
function getLastSunday(d){
var t = new Date(d);
t.setDate(t.getDate() - t.getDay());
return t;
}
修改
原来的答案有一个不正确的版本添加时间,这增加了一天,但不是OP想要的。
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?
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 lastSunday
as 23:00 on Saturday.
So what IS the safest and most efficient way to determine last Sunday?
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:
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.
这篇关于得到最近发生的星期天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!