如何获取本周(或在某些情况下为前一周)的星期一,无论本周是从星期日还是星期一开始
我有今天= new Date()
对象。无论星期日还是星期一,我都需要获得当前一周的星期一。如果一周在星期日开始,而今天的是星期天,我需要在上一周获得星期一。星期日应该永远是最后一天。关于如何解决这个问题有什么建议吗?
现在,我使用了这个,至少在星期一开始时可以正常工作。
// Get the monday date of current week
function getMondayOfCurrentWeek(d) {
const date = new Date(d);
const day = date.getDay(); // Sunday - Saturday : 0 - 6
// Day of month - day of week (-6 if Sunday), otherwise +1
const diff = date.getDate() - day + (day === 0 ? -6 : 1);
return new Date(date.setDate(diff));
}
console.log(
getMondayOfCurrentWeek(new Date(2022,3,3)).toDateString()
);
I have let today = new Date()
object. I need to get the Monday of the current week regardless if the week starts on Sunday or Monday. If the week starts on a Sunday and the today
is Sunday I need to get the Monday on the previous week. Sunday should always be the last day. Any suggestions on how to solve this?
Now I use this, which at least works fine when the week starts on Monday.
// Get the monday date of current week
function getMondayOfCurrentWeek(d) {
const date = new Date(d);
const day = date.getDay(); // Sunday - Saturday : 0 - 6
// Day of month - day of week (-6 if Sunday), otherwise +1
const diff = date.getDate() - day + (day === 0 ? -6 : 1);
return new Date(date.setDate(diff));
}
console.log(
getMondayOfCurrentWeek(new Date(2022,3,3)).toDateString()
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码确实在星期日获得了前一个星期一,
“如果一周在星期日开始”对您的意思是什么?
在JS星期日是第0或第一天
Your code DOES get the previous Monday on a Sunday
What does "If the week starts on a Sunday" mean to your?
In JS Sunday is the 0th or first day