0

Why does JavaScript return 'Invalid Date' when setting an (invalid) date? Seems like it should error out/throw an exception and makes it hard to handle any errors.

Question: What is the best way to handle this to run a check on the date value after you 'new it up' to see if the value is actually a date or a string value of 'Invalid Date'?

const validDate = new Date();
console.log('validDate instanceof Date:', validDate instanceof Date);

const invalidDate = new Date('asdfasdfasdf');
console.log('invalidDate instanceof Date:', invalidDate instanceof Date);

if (invalidDate) {
  // This hits because invalidDate is now a string and is therefore truthy
  console.log('Date is Valid');
}

if (invalidDate instanceof Date) {
  // This hits because it's still an instance of date (although the value is a string)
  console.log('Date is Valid');
}

if (typeof invalidDate === 'string') {
  // Doesnt hit because invalidDate is not a string
}
mwilson
  • 12,295
  • 7
  • 55
  • 95
  • Your `if (invalidDate)` test works **not** because it's a string, but because it's an instantiated Date instance. I mean, your own code shows that that's true. – Pointy Sep 05 '18 at 22:26
  • If `new Date(...)` doesn't throw an exception, the only possible return value is an instantiated object of some type. It won't be a string. – Pointy Sep 05 '18 at 22:27
  • It just seems like `new Date()` should throw some type of exception rather than just returning 'Invalid Date.' Just seemed kind of odd... – mwilson Sep 05 '18 at 22:31
  • 2
    Read the specification. https://www.ecma-international.org/ecma-262/6.0/#sec-date.prototype.tostring – epascarello Sep 05 '18 at 22:33
  • Well exceptions make optimization very hard, so in that sense this is actually to your benefit. Checking the date instance for invalidity this way is much cheaper than relying on an exception. – Pointy Sep 05 '18 at 22:36
  • 1
    Check this out: https://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript – Andreas Rau Sep 05 '18 at 22:39
  • @AndreasRau: Thanks, I just ran across that as well. That's got the solution I'm after. I'm flagging this as a dupe. – mwilson Sep 05 '18 at 22:40

1 Answers1

0

try with this code:

const invalidDate = new Date('aksjdhaksjdh');
console.log('invalidDate instanceof Date:', invalidDate.setUTCHours(0) instanceof Date);

The setUTCHours() method sets the hour of a date object, according to the UTC time. In this case, as our var is invalid, it can not be converted and returns false.