Reputation: 1995
Using HTML, javascript and jQuery I am importing a date from MS excel using "xlsx.full.min.js". I have set the date field in MS Excel to text so MS Excel does not change its format when exported. Once imported I then parse the table created to validate each field. To validate the date field I use:
var dateFormat = 'DD/MM/YYYY';
alert("$(this).text(): " + $(this).text());
alert(moment(moment($(this).text()).format(dateFormat),dateFormat,true).isValid());
When the MS Excel date field contains "13/12/2018" false is returned. When the MS Excel date field contains "12/13/2018" true is returned. Both these values are displayed in the alert so I know they are being passed correctly.
As I have set the date format to "DD/MM/YYYY" why does that format fail and "MM/DD/YYYY" pass?
Upvotes: 2
Views: 3622
Reputation: 141
MomentJS converts the date from string into its object before performing operations on it. If format is not specified, it assumes default formats. The parse operation is explained here: https://momentjs.com/docs/#/parsing/string/
So, in your case you have to pass the dateformat while moment object is created. Like this:
var dateFormat = "DD/MM/YYYY";
moment("12/13/2018",dateFormat).isValid() //will return false
moment("13/12/2018",dateFormat).isValid() //will return true
Update:
MomentJS allows date to be parsed even if the specified date contains other characters apart from the format. For eg., "1A/2B/2018" will be considered as a valid date as "1/2/2018".
Inorder to avoid that, and check the format and date to match exactly, moment object should be passed an additional boolean to enable strict mode.
moment("1A/2B/2018", dateFormat).isValid() //will return true
moment("1A/2B/2018", dateFormat, true).isValid() //will return false
Upvotes: 3