简体   繁体   English

我如何比较两个日期 - 它们应该在日期或年份匹配

[英]How can i compare two dates - they should match on day or year

I have the following dates我有以下日期

var date1 = moment(new Date(2019, 4, 17).valueOf());
var date2 = moment(new Date(2019, 4, 17).valueOf());

if i use如果我使用

 if (date1.isSame(date2)) {
      c.log('same')
    } else {
      c.log('not same')
      // They are not on the same day
    }

then they will be same.那么它们将是相同的。

But how can i match - true when the year is different但我怎么能匹配 - 当年份不同时是真的

var date1 = moment(new Date(2029, 4, 17).valueOf());
    var date2 = moment(new Date(2019, 4, 17).valueOf());

this should give true because they are both on 17 day.Even the year is different.这应该是真的,因为它们都在 17 天。即使年份也不一样。 This should also remain true这也应该保持正确

var date1 = moment(new Date(2019, 4, 17).valueOf());
var date2 = moment(new Date(2019, 4, 17).valueOf());

You can try this你可以试试这个

var date1 = moment(new Date(2019, 4, 17).valueOf()).format('MM/DD');
var date2 = moment(new Date(2019, 4, 17).valueOf()).format('MM/DD');

if  (date1 === date2) 
    console.log('true'); 
else 
     console.log('false');

you could compare month and day to check if they're same, no matter the year:无论年份如何,您都可以比较月份和日期以检查它们是否相同:

if (date1.format('M') ===  date2.format('M') && date1.format('D') ===  date2.format('D'))
    console.log('day and month are the same')

EDIT: changed bug in condition编辑:更改条件错误

You should check if month which is represented by the format token M and day of month represented by the format token D are the same like this您应该检查由格式标记M表示的month和由格式标记D表示day of month中的日期是否与此相同

if(date1.format('M') === date2.format('M') && date1.format('D') === date2.format('D')){
    // Your code goes here after
}

If they are the same that means It's the same day of the same month whatever the year如果它们相同,则意味着无论年份如何,都是同一个月的同一天

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

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