【问题标题】:Conditional date in a string based on distance to date?基于到日期距离的字符串中的条件日期?
【发布时间】:2020-10-21 20:18:18
【问题描述】:

搜索这个并没有取得太多成果。希望您能提供帮助!

我希望生成这样的句子:

下周一的会议从 10 月 19 日星期一开始[1],持续 7 周,直到 11 月 30 日星期一[2]

其中 [1] 是下周一的日期,除非该周一是未来 4 天或更短的时间,在这种情况下,它将是下周一。而且,[2] 是 [1] 中提到的星期一之后的 7 周。

作为奖励,如果它在一周中的其他日子也能正常工作,那就太棒了!

日期可以基于客户端浏览器。我希望在网站的客户端 JS 中完全实现这一点。

任何帮助或正确方向的指示?

【问题讨论】:

标签: javascript


【解决方案1】:

let date = new Date();
let nextMonday = new Date();
let daysToNextMonday = new Date();

nextMonday.setDate(date.getDate() + (1 + 7 - date.getDay() % 7));
let diffTime = Math.abs(nextMonday - date);

daysToNextMonday = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); //full days, no fractions


if (daysToNextMonday <= 4) {
  nextMonday.setDate(nextMonday.getDate() + 7);
}

let sevenWeeksAfter = new Date(nextMonday);
sevenWeeksAfter.setDate(nextMonday.getDate() + 7 * 7);

const monthNextMonday = new Intl.DateTimeFormat('en', {
  month: 'long'
}).format(nextMonday);
const dayNextMonday = new Intl.DateTimeFormat('en', {
  day: '2-digit'
}).format(nextMonday);

const monthSevenWeeksAfter = new Intl.DateTimeFormat('en', {
  month: 'long'
}).format(sevenWeeksAfter);
const daySevenWeeksAfter = new Intl.DateTimeFormat('en', {
  day: '2-digit'
}).format(sevenWeeksAfter);

let text = `The next Monday session starts on Monday ${monthNextMonday} ${dayNextMonday}th and runs for 7 weeks until Monday ${monthSevenWeeksAfter} ${daySevenWeeksAfter}th`;

console.log(text);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多