I have a scenario where I need to detect a particular string is date or not. I have used new Date() function, but for some strings having a particular pattern, I am getting a valid date even though it is not. For egs: new Date('Column 1') gives the output as Mon Jan 01 2001 00:00:00 GMT 0530 (India Standard Time). Is there any way to solve this? Is tere any particular regex pattern that we can use in these situation?
Thanks in advance Saumya
CodePudding user response:
function isDate(dateStr) {
return !isNaN(new Date(dateStr).getDate());
}
This may work.
CodePudding user response:
just use Date.parse()
, which return millisecond if date is valid other wise return NaN
console.log(Date.parse('2020-01-01'))
console.log(Date.parse('abc'))
CodePudding user response:
Use Moment.js
https://momentjs.com/docs/#/displaying/format/
Example