如何获取本周(或在某些情况下为前一周)的星期一,无论本周是从星期日还是星期一开始

发布于 2025-01-19 12:49:47 字数 663 浏览 0 评论 0原文

我有今天= 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

独夜无伴 2025-01-26 12:49:47

您的代码确实在星期日获得了前一个星期一,

“如果一周在星期日开始”对您的意思是什么?

在JS星期日是第0或第一天

// 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 date.setDate(diff), date;
}

console.log(getMondayOfCurrentWeek(new Date()).toDateString() )

console.log(getMondayOfCurrentWeek(new Date(2022,3,3,15,0,0,0)).toDateString() ); // Sunday 3rd of April 2022

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

// 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 date.setDate(diff), date;
}

console.log(getMondayOfCurrentWeek(new Date()).toDateString() )

console.log(getMondayOfCurrentWeek(new Date(2022,3,3,15,0,0,0)).toDateString() ); // Sunday 3rd of April 2022

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文