javascript - Determine if string is Date or Number -
i'm trying determine if string number or date.
here code:
this._getfieldformat = (value) => { // check if date let d = new date(value); if (!isnan( d.gettime() ) ) { return 'date'; } // check if boolean // isnan(false) = false, false number (0), true number (1) if(typeof value === 'boolean'){ return 'boolean'; } // check if string number if(!isnan(value)){ return 'number'; } return typeof value; };
it works date like: 2016-04-19t23:09:10.208092z
. problem 1
valid date (wed dec 31 1969 16:00:00 gmt-0800 (pst)
) , isnan(new date())
return false
(a date number).
any idea on how out of loop?
so happening called coercion. since javascript dynamic typing when give 2 different types js engine tries coerce 1 of types reasonable or thought meant.
for instance:
isnan("37"); false because "37" converted number 37
isnan(new date()) return false (a date number)
it converted date number correct.
however, invalid values in date strings not recognized iso format defined ecma-262 may or may not result in nan, depending on browser , values provided
so
new date('23/25/2014'); // non-iso string invalid date values
so return nan in browsers comply es5 , later.
also stricter check can use:
number.isnan(new date()); // should return true
so recap make sure date conform iso standard or nan , use stricter check. hope helps.
Comments
Post a Comment