繁体   English   中英

Moment.js 根据给定的工作日和日期获取日期

[英]Moment.js get the date based on the given weekday and date

我想根据给定的工作日和日期获取日期。 比方说:

const date = "2022-08-29"; // Monday
const week = "Wednesday"; OR const week = 3;

结果日期应为“2022-08-31”,因为该周的星期三是 31 日。

我已经尝试添加一些日子,但我可以说这不是正确的方法,因为如果日期将在以后开始,让我们说:

const date = "2022-08-31"; // Wednesday
const week = "Tuesday"; OR const week = 2;

然后从 31 日开始添加 2 天,将导致 2022-09-02,即 9 月 2 日。 正确的结果是 2022-08-30,因为该周的星期二是 30 日。 如何实现这一目标?

将日期倒回一周的开始,然后添加天数以使其达到指定日期。

可以使用Date.prototype.getDay()确定一周中的当前日期。

 const days = {Monday: 1, Tuesday: 2, Wednesday: 3, Thursday: 4, Friday: 5, Saturday: 6, Sunday: 7}; const getDayOfWeek = (dateStr, weekDay) => { // turn string values into a day offset // subtract 1 to get offset from the start of the week const dayOffset = (typeof weekDay === "number"? weekDay: days[weekDay]) - 1; // Parse date string const date = new Date(dateStr); // Offset for Monday as the start of the week const weekStartOffset = (date.getDate() + 6) % 7; // Alter the date date.setDate(date.getDate() - weekStartOffset + dayOffset); return date; }; console.info("Week of Monday 29th Aug -> Wednesday"); console.log(getDayOfWeek("2022-08-29", "Wednesday")); console.info("Week of Wednesday 31st Aug -> Tuesday"); console.log(getDayOfWeek("2022-08-31", "Tuesday")); console.info("Week of Sunday 28th Aug -> Monday"); console.log(getDayOfWeek("2022-08-28", "Monday"));
 .as-console-wrapper { max-height: 100%;important; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM