如果日期是本周,本月或今年,则会获得

时间:2017-11-03 13:42:59

标签: javascript date momentjs

我正在尝试将随机日期值传递给片刻,并检查日期是本周,本月还是今年,但似乎没有简单的功能可以在不写大量功能的情况下实现,但是因为我是初学者我不知道。

现在唯一对我有用的就是这样的一周

moment(somedate, "MM-DD-YYYY").week() // 44

我可以将它与今天的日期周比较

moment(todaysDate, "MM-DD-YYYY").week() // 44

并检查值是否相同以确定日期是否在本周

但我的问题是我必须和月份和年份相同而且它有点麻烦,我想通过寻找任何回答来解决问题。

3 个答案:

答案 0 :(得分:9)

您可以使用查询(查看docs

moment(dateToCheck).isSame(new Date(), 'week'); //true if dates are in the same week
moment(dateToCheck).isSame(new Date(), 'month'); //true if dates are in the same month
moment(dateToCheck).isSame(new Date(), 'year'); //true if dates are in the same year

答案 1 :(得分:4)

使用.isSame()

  

检查片刻是否与另一时刻相同。

     

moment().isSame(Moment|String|Number|Date|Array);   moment().isSame(Moment|String|Number|Date|Array, String);

     

支持的单位:year month week day hour minute second

moment('2010-10-20').isSame('2010-01-01', 'year');  // true
moment('2010-01-01').isSame('2011-01-01', 'month'); // false, different year
moment('2010-01-01').isSame('2010-02-01', 'day');   // false, different month

答案 2 :(得分:0)

尝试使用moment isSame()方法检查日期是否有限制。

首先,您必须在项目中添加 moment 依赖项。

npm install moment --save   # npm
yarn add moment             # Yarn
Install-Package Moment.js   # NuGet
spm install moment --save   # spm
meteor add momentjs:moment  # meteor
bower install moment --save # bower (deprecated)

将其导入您的组件

import moment from 'moment'

moment 是相同的方法语法,

moment().isSame(Moment|String|Number|Date|Array);
moment().isSame(Moment|String|Number|Date|Array, String);

检查一个时刻是否与另一个时刻相同。第一个参数将被解析为片刻,如果还没有的话。

moment(dateVal).isSame(new Date(), 'week'); //true if dates are in the same week
moment(dateVal).isSame(new Date(), 'month'); //true if dates are in the same month
moment(dateVal).isSame(new Date(), 'year'); //true if dates are in the same year

dateVal 是您要在当前周、月或年中检查的日期。

例如:假设您要检查“20-5-2021”是否在当前周、月和年。你可以这样检查。

moment('20-5-2021').isSame(new Date(), 'week');
moment('20-5-2021').isSame(new Date(), 'month'); 
moment('20-5-2021').isSame(new Date(), 'year');