isSame() function in moment.js or Date Validation

前端 未结 1 529
清酒与你
清酒与你 2020-12-25 10:57

I need to validate the date from the user and check if it is in a particular format. If yes, then it will be accepted else it will not be. I am looking for sort of

相关标签:
1条回答
  • 2020-12-25 11:40

    Docs - Is Same

    Check if a moment is the same as another moment.

    moment('2010-10-20').isSame('2010-10-20'); // true

    If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

    moment('2010-10-20').isSame('2009-12-31', 'year'); // false
    moment('2010-10-20').isSame('2010-01-01', 'year'); // true
    moment('2010-10-20').isSame('2010-12-31', 'year'); // true
    moment('2010-10-20').isSame('2011-01-01', 'year'); // false

    Your code

    var x=moment("28-02-1999","DD-MM-YYYY"); // working
    x.isSame("28-02-1999"); // comparing x to an unrecognizable string
    

    If you try moment("28-02-1999"), you get an invalid date. So comparing x to an invalid date string returns false.

    To fix it, either use the default date format (ISO 8601):

    var x = moment("28-02-1999","DD-MM-YYYY");
    x.isSame("1999-02-28"); // YYYY-MM-DD
    

    Or pass isSame a moment object.

    var x = moment("28-02-1999","DD-MM-YYYY");
    x.isSame( moment("28-02-1999","DD-MM-YYYY") );
    
    0 讨论(0)
提交回复
热议问题