Check if date is a valid one

前端 未结 9 649
再見小時候
再見小時候 2020-12-13 11:52

Following is the scenario:

I have a String date and a date format which is different. Ex.:
date: 2016-10-19
dateFormat: \"DD-MM-YYYY\".

相关标签:
9条回答
  • 2020-12-13 12:24

    Was able to find the solution. Since the date I am getting is in ISO format, only providing date to moment will validate it, no need to pass the dateFormat.

    var date = moment("2016-10-19");
    

    And then date.isValid() gives desired result.

    0 讨论(0)
  • 2020-12-13 12:26

    I just found a really messed up case.

    moment('Decimal128', 'YYYY-MM-DD').isValid() // true
    
    0 讨论(0)
  • 2020-12-13 12:26

    Try this one. It is not nice but it will work as long as the input is constant format from your date picker.

    It is badDate coming from your picker in this example

    https://jsfiddle.net/xs8tvox9/

    var dateFormat = 'DD-MM-YYYY'
    var badDate = "2016-10-19";
    
    var splittedDate = badDate.split('-');
    
    if (splittedDate.length == 3) {
      var d = moment(splittedDate[2]+"-"+splittedDate[1]+"-"+splittedDate[0], dateFormat);
      alert(d.isValid())
    } else {
      //incorrectFormat
    }
    
    0 讨论(0)
提交回复
热议问题