0

I have a script which is meant to distinguish date, number and string formats. When i wanted to check if a user input is date or not, i have faced a rare case in the program.

What i did to check, if user given string can be converted to date, was a simple condition though.

if(!(new Date(userInputValue)=='Invalid Date'));

{ userInputValue = new Date(userInputValue); }

Let's say, if user gives an input as 'JS 53'

The code new Date('JS 53') converts the string input to Thu Jan 01 1953 00:00:00 GMT+0100 (Central European Standard Time)

If user gives an input as '53 JS'

The code new Date('53 JS') gives Invalid Date which is what i expected. Why placement of numbers and strings in a whole string makes a difference ?

Can777
  • 146
  • 11
  • 3
    Read the [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date): *"parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. "*. The code you display is a strong malpractice. Either you parse correctly the string or you use a well tested library (like Moment). – Denys Séguret May 24 '19 at 08:18
  • 1
    Use a datepicker for dates, rather than letting the user enter it as text. – Barmar May 24 '19 at 08:20
  • @Barmar I already use a datepicker only for date cases. But in the script, because of data we need to structure, input type can be string, string plus number, number or date and i need to distinguish them. If input is string + number, i need to find a way that program understands it can not be a date. – Can777 May 24 '19 at 08:37
  • 1
    @DenysSéguret alright thanks for the advice. I will look into Moment library. – Can777 May 24 '19 at 09:01
  • See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG May 24 '19 at 20:29
  • @DenysSéguret—a library can only help if it's told the format. In the OP case, moment.js will fall back to the built–in parser, so nothing gained (and there are many other good libraries for parsing). – RobG May 24 '19 at 20:30

0 Answers0