How do I accept multiple formats of date with moment.js

Viewed 360

I want to accept dates from the users but I cannot enforce the users to enter the date in a specific format. I have tried going through the momentjs documentation but couldn't really find how its done. I can specify an array of formats but then I'll be tied down to those specific formats only.

I know that MS Excel and many other apps does this. (Take date input in some format and convert it to the application suitable format)

If not with moment.js how else can I achieve this? What could be the algorithm or logic that can achieve this thing.

Thanks!

1 Answers

Moment.js can parse an ambiguous string as a date if you don't specify expected formats. It will first attempt to parse it as an ISO 8601 date format, then as an RFC 2822 format and ultimately fall back to JS Date parsing. Keep in mind the supported formats in a JS Date are inconsistent between browsers.

For this reason it's highly advised to always parse using a set of expected formats and enforce the user to input in one of these. Otherwise you may end up with incorrectly parsed dates.

Related