1

I raised strange issue:

var d = new Date("2016--01---01");

Would create object without any errors. Actually, first question is - why?

But then i need to get string from this object - i am trying to

d.toString();     // 'Invalid Date'
d.getTime();      // NaN
d.toJSON();       // null

What it is possible ways to get string or check that it is incorrect?

jonny
  • 3,022
  • 1
  • 17
  • 30
alexey
  • 1,381
  • 9
  • 19

2 Answers2

1

You can simply check it's a valid number when converted to one:

var ok = !isNaN(d);

(this conversion is the same than taking d.getTime()).

But be warned that a valid date might be not the desired date. You usually use a verified date format. Libraries like moment.js might help you on that.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

Create a factory type function which throws an error if the string given produces an invalid date, but returns the date if it's valid

var d = createDate("2016--01---01")

createDate = function(str) {    
  var date = new Date(str)
  if(date instanceof Date && !isNaN(date.valueOf())) return date
  else throw Error('invalid date')
}
jonny
  • 3,022
  • 1
  • 17
  • 30