Search code examples
javascriptnode.jsmomentjsmoment-timezone

how to check the string is valid date format or not (format should be in : YYYY-MM-DD HH:mm:ss)


how do I check whether string is valid date format or not? format should be in : YYYY-MM-DD HH:mm:ss

console.log(moment(moment("FLAT 10").format('YYYY-MM-DD HH:mm:ss'),'YYYY-MM-DD HH:mm:ss').isValid())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>

enter image description here

above code should return false but its giving me output as TRUE

I tried this code too but still its failing...

enter image description here how to solve this? how to compare string and date using moment

js fiddle link: jsfiddle.net/8Lwrvcep


Solution

  • Your response will be always true because the parameter of the moment is a valid date and you are just applying a format to it and check if it is valid

    To compare dates without checking the format use:
    moment('2017-01-01T00:00:00').isSame(moment('2017-01-01T00:00:00'))

    moment('string','format you want to check for').isValid() if you don't provide format and test moment("ASD 10").isValid() this will always will be valid because it has a integer and it and converts to OCTOBER beecause as I said is the 10th month of the year

    console.log(moment("ASD 10",'YYYY-MMM DD h:mm A').isValid()); // returns false console.log(moment("ASD 10").isValid()); //returns true