繁体   English   中英

如何在 JavaScript 中检查给定日期是本周还是上周

[英]How to Check Given Date is This week or Last Week in JavaScript

我需要检查给定的日期是“今天”、“昨天”、“本周”、“上周”、“本月”、“上个月”、“九月”、“八月”、“七月”…… .. '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

等等...

也许为时已晚,但如果您没有办法,这可能对您自己有所帮助。 您可以在calendar()上支持它说:

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

默认值是:

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

当时刻距 referenceDay 超过一周时,使用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'));
 <script src="https://momentjs.com/downloads/moment.js"></script>

您也可以直接从函数返回消息而不是“时间前”字符串。

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

暂无
暂无

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

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