Moment js如何获取某个日期是否在上周的范围内


使用Moment.js可以轻松获取某个日期是否在上周的范围内。你可以按照以下步骤进行操作:

  1. 首先,使用Moment.js创建一个表示当前日期的Moment对象。可以使用moment()函数,不传递任何参数,将会创建一个表示当前日期和时间的Moment对象。例如:const currentDate = moment();

  2. 使用Moment对象的subtract()方法,将当前日期减去7天,以获取上周的日期范围的起始日期。例如:const lastWeekStart = currentDate.subtract(7, 'days');

  3. 使用Moment对象的add()方法,将当前日期加上6天,以获取上周的日期范围的结束日期。例如:const lastWeekEnd = currentDate.add(6, 'days');

  4. 最后,使用Moment对象的isBetween()方法,将要检查的日期和上周的日期范围进行比较,判断该日期是否在上周的范围内。例如:const isInLastWeek = yourDate.isBetween(lastWeekStart, lastWeekEnd);,其中yourDate是你要检查的日期。

完整的代码示例如下:

  1. const moment = require('moment');
  2. const currentDate = moment();
  3. const lastWeekStart = currentDate.subtract(7, 'days');
  4. const lastWeekEnd = currentDate.add(6, 'days');
  5. const yourDate = moment('2022-01-15'); // 替换成你要检查的日期
  6. const isInLastWeek = yourDate.isBetween(lastWeekStart, lastWeekEnd);
  7. console.log(isInLastWeek); // 输出 true 或 false,表示该日期是否在上周的范围内

BLOG

搜索文章