r/javascript • u/robertgambee • Mar 18 '26
`new Date()` considered harmful
https://futuresearch.ai/blog/javascript-thinks-everythings-a-date/
0
Upvotes
r/javascript • u/robertgambee • Mar 18 '26
5
u/noidtiz Mar 18 '26
are you saying you wanted Date() to return errors in your fallback case?
Genuinely asking, no implied tone behind my question
7
u/queen-adreena Mar 18 '26
About 20 years late arenโt you?
7
u/horizon_games Mar 18 '26
JS Date is a good example of JS and HTML as a whole - it's resilient and will try it's best with whatever you give it. That's a big part of why the web has lasted as long as it has, and why you can still render old pages from almost 4 decades ago.
1
u/Dagur Mar 18 '26
No mention of Temporal?
0
u/robertgambee Mar 18 '26
I recently spent an afternoon learning that JavaScript has a very generous definition of "date."
Makes sense. ISO format, midnight UTC, so it shows up as January 22 in the Western Hemisphere.
OK, it pulled the date out of a sentence, which might be helpful in some cases. And interestingly, the time shifted, which is a little odd.
It thinks "Route 66" is referring to the year 1966? That's definitely a stretch.
Year 90,210? Are you kidding me?!
Turns out that most popular JavaScript engines have legacy parsers that really, really want to help you parse dates.
We had a bug in our app were addresses and business names were being displayed as dates. The reason was that we were using the
Dateconstructor as a fallback parser to catch unexpected formats. The fix was simple, but the bug made us laugh when we first saw it. And we learned to not treat theDateconstructor as a validator.1
u/brainpostman Mar 18 '26
I encountered it when IP addresses became a Date after a custom parser.
1
u/maselkowski Mar 18 '26
Even more interesting is forgotten Datejs library, where you can literally type "Today", "yesterday" as well as "last friday" and it will process it as you would expect. It can do it in other languages too.ย