teone
teone

Reputation: 2183

Determine if string is Date or Number

I'm trying to determine if a string is a number or a date.

Here is my code:

this._getFieldFormat = (value) => {

  // check if is date
  let d = new Date(value);

  if (!isNaN( d.getTime() ) ) {
    return 'date';
  }

  // check if is boolean
  // isNaN(false) = false, false is a number (0), true is a number (1)
  if(typeof value  === 'boolean'){
    return 'boolean';
  }

  // check if a string is a number
  if(!isNaN(value)){
    return 'number';
  }

  return typeof value;
};

It works for a date like: 2016-04-19T23:09:10.208092Z. The problem is that 1 look to be a valid date (Wed Dec 31 1969 16:00:00 GMT-0800 (PST)) and isNaN(new Date()) is return false (a date is a number).

Any idea on how to get out of this loop?

Upvotes: 1

Views: 688

Answers (2)

anu
anu

Reputation: 1007

In general and from a Javascript design point of view, however, I don't think you can do it by design. Any number between 8640000000000000 and the earliest date in terms of a number -8640000000000000 can be converted to date (represented as time in milliseconds from 01 January, 1970 UTC).

Therefore, any number not falling is this range cannot be a date. And any number falling in range would be a valid date or a number and you gotta use context to determine if you want to interpret it as a number or a date.

You could however do a naive implementation to test if number is a valid date or not, but that's the best you can do, without context.

Determining whether a date is a number or not can be a bit easier. Because a human-readable representation of date will return true by isNaN() thereby determining that it's definitely not a number. Then you would go on and check if that string is a date or not, which you already did in your function.

Upvotes: 0

sebenalern
sebenalern

Reputation: 2561

So what is happening is called coercion. Since javascript is dynamic typing when you give it two different types the js engine tries to coerce one of the types into something reasonable or what it thought you meant.

For instance:

isNan("37"); is false because "37" is converted to the number 37

isNaN(new Date()) is return false (a date is a number)

It converted Date to a number so this is correct.

However, invalid values in date strings not recognized as ISO format as defined by ECMA-262 may or may not result in NaN, depending on the browser and values provided

So

new Date('23/25/2014'); // NON-ISO string with invalid date values

So this will return NaN in all browsers that comply with ES5 and later.

Also to do a stricter check you can use:

Number.isNan(new Date()); // This should return true

So to recap make sure the date conform to the ISO standard or it will be NaN and use the stricter check. Hope this helps.

Upvotes: 1

Related Questions