Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Chrome V8 JavaScript engine recognize "TG-1" through "TG-12" as valid dates/times?

I implemented a CSV parser that guesses the type formats for each column but I have found that the JavaScript Date class believes "TG-1" is a valid date/time.

Is this some obscure date format I haven't seen before that Chrome supports? I wouldn't think this is a valid date and looking at different date ISO standards I haven't seen a reference to this.

Chrome 74 says it's valid.

Firefox 64 says it's not valid.

let validDate = true;
try{
   d = new Date("TG-1");
   d.toISOString()
}catch(e){
   validDate = false
}
console.log(validDate);

Any string followed by - and a number 1-12 is considered valid:

d = new Date("adsfadgag-12")//valid per V8
like image 781
desean Avatar asked Nov 06 '22 17:11

desean


1 Answers

To quote from the V8 sourcecode:

Legacy dates:

Any unrecognized word before the first number is ignored.

Parenthesized text is ignored.

An unsigned number followed by ':' is a time value, and is added to the TimeComposer. A number followed by '::' adds a second zero as well. A number followed by '.' is also a time and must be followed by milliseconds.

Any other number is a date component and is added to DayComposer. A month name (or really: any word having the same first three letters as a month name) is recorded as a named month in the Day composer. A word recognizable as a time-zone is recorded as such, as is (+|-)(hhmm|hh:).

Legacy dates don't allow extra signs ('+' or '-') or umatched ')' after a number has been read (before the first number, any garbage is allowed).

Intersection of the two: A string that matches both formats (e.g. 1970-01-01) will be parsed as an ES5 date-time string - which means it will default to UTC time-zone. That's unavoidable if following the ES5 specification.

After a valid "T" has been read while scanning an ES5 datetime string, the input can no longer be a valid legacy date, since the "T" is a garbage string after a number has been read.

In other words: This behaviour is not really planned, it's just that some browsers behaved like this somewhen, and therefore this weird behaviour has to be kept. Date(...) will try to parse nearly anything without complaining.

like image 59
Jonas Wilms Avatar answered Nov 12 '22 20:11

Jonas Wilms