1

The implementation of Date.parse in Chrome has very unexpected behavior.

For example, Date.parse('foo 2014') should ideally return NaN as it is not a proper date format. But in Chrome this returns the value 1388514600000, which is equivalent to the date "Wed Jan 01 2014 00:00:00 GMT+0530 (India Standard Time)".

As long as the string ends with some sort of year, a proper date value is returned. This will not let us to properly validate dates.

According to ECMAScript this behavior is implementation dependent and chrome does a very loose validation and some how converts to a date.

Is there anyway in chrome to properly validate date without using any library or using heavy logic and matching patterns?

Anand N
  • 380
  • 1
  • 4
  • 12
  • One possible way might be using Date.UTC 1. var a = Your format of date 2. Split it in whatever delimited you have ( extract month , date, year ) 3. var date=new Date(Date.UTC('2014','foo'.......) console.log(date) -- Prints Invalid date However you have to validate the Month and Date Range which should be easy – user1428716 Jan 10 '15 at 13:10
  • @user1428716, the problem is the format can be anything. The data is coming from Excel file and if user enters it as a string, we need to parse it into a proper date... – Anand N Jan 11 '15 at 14:38

1 Answers1

0

You can test date string with regular expression before parse.

Tarwirdur Turon
  • 751
  • 5
  • 17
  • the problem is that the format of date can be anything...the data is received from Excel and if user enters the date as string, we need to parse it into proper date... – Anand N Jan 11 '15 at 14:39
  • @Anand, you can use several regular expressions for different formats. – Tarwirdur Turon Jan 11 '15 at 19:38