【问题标题】:How to Check Given Date is This week or Last Week in JavaScript如何在 JavaScript 中检查给定日期是本周还是上周
【发布时间】:2020-11-02 18:21:21
【问题描述】:

我需要检查给定的日期是'今天','昨天','本周','上周','本月','上个月','九月','八月', 'Jul', .... '2019', '2018', 等......在 JavaScript 中。

我正在使用 Moment js 来显示日期时间

moment.tz(message.receivedDateTime, 'America/Denver').format("hh:mm A")

我们有一个消息数组,其中包含收到消息的内容和日期,因此我们需要检查日期并在 JavaScript 中显示如下格式的消息列表。

Today
    Message 1 
    Message 2
Yesterday
    Message 3
    Message 4
This Week
    Message 5
Last Week
    Message 6
    Message 7

等等……

【问题讨论】:

标签: javascript momentjs


【解决方案1】:

也许为时已晚,但如果你没有办法,这可能对你自己有帮助。你可以支持calendar(),上面写着:

日历时间显示相对于给定参考日的时间(默认为今天的开始时间)。 [...] 注意:从 2.25.0 版本开始,您只能传递格式参数,它可以是字符串和函数的对象。

默认值是:

moment().calendar({
    sameDay: '[Today]',
    nextDay: '[Tomorrow]',
    nextWeek: 'dddd',
    lastDay: '[Yesterday]',
    lastWeek: '[Last] dddd',
    sameElse: 'DD/MM/YYYY'
});

sameElse 用于当时刻距参考日超过一周时的格式。

difference() 以毫秒或其他测量单位为单位获得差异。

因此,对于少于一周(或 7 天)的情况,您可以使用 lastWeek,对于超过一周的情况,请使用 sameElse,如下所示:

function calendarDate(date) {
  return moment(date).calendar({
    sameElse: function (now) {
      const from = moment(this);
      now = moment(now);
      const dayDiff = now.diff(from, 'days');
      if (dayDiff >= 7 && dayDiff <= 14) {
        return '[Last week]';
      } else {
        const monthDiff = now.diff(from, 'months', true);
        if (monthDiff === 0) {
          return '[This month]';
        }
        if (monthDiff > 0 && monthDiff <= 1) {
          return '[Last Month]';
        }
        if (monthDiff > 1) {
          if (Number(from.format('YYYY')) - Number(now.format('YYYY')) < 0) {
            return `[${from.format('YYYY')}]`;
          }
          return `[${from.format('MMMM')}]`;
        }
      }
      return '[More than a week]';
    },
  });
}

console.log(calendarDate('2020-11-01'));
console.log(calendarDate('2020-10-23'));
console.log(calendarDate('2020-09-30'));
&lt;script src="https://momentjs.com/downloads/moment.js"&gt;&lt;/script&gt;

您也可以直接从函数返回消息,而不是“time ago”字符串。

请记住,这只是一个示例,您可以根据需要调整范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2012-02-27
    相关资源
    最近更新 更多