momentjs get if date is this week, this month or t

2019-02-27 19:22发布

问题:

I am trying to pass random date values to moment and check if the date is this week, this month or this year but it seems there is no simple function to achive this without writing lots of function, but since I am a beginner I don't know.

The only thing that is working for me right now is getting the week like this

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

and I can compare that with todays date week

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

and check if the values are the same to determine if the date is withing this week

but my problem is that I have to the the same to month and year and it's a bit cumbersome and I want to try to fix issue by looking for any answeres.

回答1:

You can use queries (check 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


回答2:

Use .isSame()

Check if a moment is the same as another moment.

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

Supported units: 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