This article lists several of the absurdities of the Date constructor, but only barely touches on the most unforgivable one. The example from the article is:
// Unless, of course, you separate the year, month, and date with hyphens.
// Then it gets the _day_ wrong.
console.log( new Date('2026-01-02') );
// Result: Date Thu Jan 01 2026 19:00:00 GMT-0500 (Eastern Standard Time)
In this example, the day is "wrong" because the constructor input is being interpreted as midnight UTC on January 2nd, and at that instantaneous point in time, it is 7pm on January 1st in Eastern Standard Time (which is the author's local time zone).
What's actually happening here is a comedy of errors. JavaScript is interpreting that particular string format ("YYYY-MM-DD") as an ISO 8601 date-only form. ISO 8601 specifies that if no time zone designator is provided, the time is assumed to be in local time. The ES5 spec authors intended to match ISO 8601 behavior, but somehow accidentally changed this to 'The value of an absent time zone offset is “Z”' (UTC).
Years later, they had realized their mistakes, and attempted to correct it in ES2015. And you can probably predict what happened. When browsers shipped the correct behavior, they got too many reports about websites which were relying on the previous incorrect behavior. So it got completely rolled back, sacrificed to the altar of "web compatibility."
For more info, see the "Broken Parser" section towards the bottom of this article:
>So it got completely rolled back, sacrificed to the altar of "web compatibility."
This is why I don't understand the lack of directives.
'use strict'; at the top of a file was ubiquitous for a long time and it worked. It didn't force rolling back incompatibilities, it let you opt into a stricter parsing of JavaScript.
It would have been nice for other wide changes like this to have like a 'strict datetime'; directive which would opt you into using this corrected behavior.
They couldn't and shouldn't do this sort of thing for all changes, but for really major changes to the platform this would be an improvement.
Or they could go all in on internal modules, like how you can import `node:fs` now. They could include corrected versions of globals like
`import Date from 'browser:date';`
has corrected behavior, for example
WorldMaker [3 hidden]5 mins ago
To be fair, the new opt-in "use strict" here is "switch to Temporal". It's a new, stricter namespace object. Old Date code gets the old Date code quirks, new code gets the nice new Temporal API.
Internal modules would be handy in theory to maybe keep from having to dig through a thesaurus every time browsers decide to add a new, stricter version of an older API. Internal modules have even been proposed to TC-39 as a recommended way to continue to expand the JS API. Last I checked on that proposal it was stuck behind several concerns including:
1. Feature detection: detecting if Temporal available is as easy as `if ('Temporal' in globalThis) {}`, but detecting if a module import is missing is a bit harder. Right now the standard is that loading a module fails with an Error if one of its imports fails. You can work around that by doing a dynamic import inside a try/catch, but that's a lot of extra boilerplate compared to `const thingINeed = 'someApi' in globalThis ? someApi() : someApiPolyfill()`. I've seen multiple proposals on that front from extensions to import maps and `with { }` options on the import itself.
2. Bikeshedding (and lots of it): defining a URI scheme like `browser:` or `standard:` takes a bunch of thought on how you expand it. If it is just `browser:some-api` you run the risk of eventually polluting all the easy names in the exact way people worry about the risk of over-polluting `globalThis` (and in the way that it can be weirdly hard to find an available one-word name on npm), you've just moved the naming problem from one place to the other. On the other side, if you go down the road of something like `es-standard:https://tc39.es/ecma262/2025/v1/final-draft/Temporal`, even (especially) assuming users would mostly importmap that to something shorter you've recreated XMLNS URIs in a funny new hat and people who use JS all certainly have plenty of opinions on XMLNS URIs, many are very vocal in their hatred of it, but also they came out of a strong backwards incompatibility fixing desire exactly like this. (As they say time is a flat circle.)
echelon [3 hidden]5 mins ago
> To be fair, the new opt-in "use strict" here is "switch to Temporal".
This. Don't break old code, just provide new best practices.
Update linters (or ideally first class language rules, like in Rust's "edition"s), to gradually kill off old behavior. Without having to do a decade long Python 2 -> 3 migration.
Temporal is nice. It learned from the many failures and dead bodies that came before it. And it had lots of good implementations to look at: Joda Time, Chrono, etc.
abuob [3 hidden]5 mins ago
I find it very unfortunate that browsers (or rather, the spec) do not support some kind of versioning. If we could declare which version of HTML, JS and CSS to use, it would allow for breaking changes without breaking the entire web.
There are so many (in hindsight bad) design choices and implementation accidents that currently exist in perpetuity because of backwards compatibility; the web would really benefit if every now and then we could shed old baggage.
josephg [3 hidden]5 mins ago
> It would have been nice for other wide changes like this to have like a 'strict datetime'; directive which would opt you into using this corrected behavior.
That would be ugly, because you'd want some parts of your program (eg libraries) to use the old behaviour, and other parts might want the new behaviour. How would you minify multiple modules together if they all expect different behaviour from the standard library?
In my opinion the right way to do this is to have multiple constructors (as Obj-C, swift, C and rust all do). Eg:
let d = new Date(...) // old behaviour (not recommended for new code)
let d = Date.fromISOString(...) // fixed behaviour
The big downside of this is that its tricky to keep track of which fields and functions people should really stop using in modern javascript. It'd be nice if there was a way to enable more shouty warnings during development for deprecated JS features.
hnlmorg [3 hidden]5 mins ago
This was the approach Perl took and much as I love(d) that language, it do get pretty out of hand after a while if you wanted to adopt any newer or stricter language features.
AceJohnny2 [3 hidden]5 mins ago
> it do get pretty out of hand after a while if you wanted to adopt any newer or stricter language features.
How does it get out of hand?
FWIW, I just do `use v5.32;` or similar to opt-in to everything from that version.
Of course, if you instead want to pick-and-choose features, then I can see the list growing large.
thayne [3 hidden]5 mins ago
Maybe something like rust's editions, where you can opt into a set of breaking changes made at a certain time.
OptionOfT [3 hidden]5 mins ago
I very much remember coding a function that split the string on their components and then rebuild them to ensure the date was created without time zone.
Sometimes a date is just a date. Your birthday is on a date, it doesn't shift by x hours because you moved to another state.
The old Outlook marked birthdays as all-day events, but stored the value with time-zone, meaning all birthdays of people whose birthday I stored in Belgium were now shifted as I moved to California...
abustamam [3 hidden]5 mins ago
I always found it weird when systems code dates as DateTime strings. There needs to be a different primitive for Date, which is inherently timezone-less, and DateTime, which does require a timezone.
After having a bunch of problems with dealing with Dates coded as DateTime, I've begun coding dates as a Date primitive, and wrote functions for calculation between dates ensuring that timezone never creeps its way into it. If there is ever a DateTime string in a Date column in the database, it's impossible to know what the date was supposed to be unless you know you normalized it at some point on the way up.
Then I found that a lot of DatePicker libraries, despite being in "DATE" picker mode, will still append a local timezone to its value. So I had to write a sanitizer for stripping out the TZ before sending up to the server.
That said, I am pretty excited about Temporal, it'll still make other things easier.
cpmsmith [3 hidden]5 mins ago
Temporal does have PlainDate, which is the Date primitive you're describing (by a different name, presumably to not collide with the old Date type).
There needs to be a difference between an Instant, an Instant at an Observed Location, and a 'Specification for constructing a date that might or might not have already passed or pass in the future'.
E.G. in a conversation "Lets open the shop at 9am every day that it isn't closed." Is a fairly simple recurrence, with some exceptions*. If timezones change the scheduled time remains evaluated again on each day.
abustamam [3 hidden]5 mins ago
Yeah that's a good point, and also takes into account the dreaded DST (what are this business's operating hours for example, which remains the same locally but would change in UTC)
eszed [3 hidden]5 mins ago
I mean... That's kinda how it works? More than once I've halfway forgotten birthdays of friends who live in timezones to my east, and then sent them a message saying "Happy birthday! (It still is where I am, lol)".
I'm not necessarily defending the implementation, just pointing out another way in which time is irreducibly ambiguous and cursed.
layman51 [3 hidden]5 mins ago
You reminded me of some riddle I had once read that was about trying to figure out how someone could be born one year later but still be older than someone born in previous year. The answer to the riddle also relies on timezones. For sure, birthdates involve time zones.
The riddle explanation was something like: A baby is born in New York City at 12:15 AM on January 1. Thirty minutes later, another baby is born in Los Angeles, where the local time is 9:45 PM on December 31. Although the New York baby is actually older by 30 minutes, the calendar dates make it appear as though the Los Angeles baby was born first.
WorldMaker [3 hidden]5 mins ago
The other biggest fun trick of timezone math to a riddle like that would be the International Date line where a baby born on one side of it can be born on the "day before" by calendar reckoning despite being born 30 minutes after the other side of the line.
rmunn [3 hidden]5 mins ago
Fraternal (not identical) twins, born aboard a ship traveling west to east across the Pacific. One of them officially born January 1st, 2016. The younger-by-30-minutes twin officially born December 31st, 2015. They'll have the hardest time persuading people that they're really twins once they're grown up.
hdjrudni [3 hidden]5 mins ago
This works even without timezones. If they're born even a second apart, it can so happen on different days (if they're born around midnight)
rmunn [3 hidden]5 mins ago
Yes, and if you ask any midwife, OB/GYN, or other person who routinely delivers babies, I'm sure you'll hear about plenty of born-on-different-days twins. One of my in-laws is a doctor who delivers babies; she has lots of stories, some of which she's restricted by HIPAA from sharing. But once a baby is born, the baby's birth date is public knowledge so she can share that info. So she often will tell her husband, "My patient is going into labor, I have to go to the hospital" without naming the patient. Then after the baby is born she'll say "Mrs. Smith's baby was born at 11 PM last night" because now it's a matter of public record who the mother was, whereas before it was protected by HIPAA. Next time I talk to her, I'll ask her if she's ever personally delivered any twins with different birthdays.
The timezones thing, of course, is just a way to have the younger twin be born "a year ahead" of the older twin by having their births be in two different timezones. Only practical way that would happen would be aboard a ship, because 1) babies born aboard an airplane would probably end up using the time zone of departure or of destination for their birth, and so twins would not be counted as being born in different time zones. And 2) any land-based transportation such as a car or a train would likely pull over (or in the case of a train, let the pregnant woman off at the nearest station) so that the woman giving birth doesn't have to do so in a moving vehicle. So a ship is the only moving vehicle where this kind of thing could likely happen, as there's no option of getting off in the middle of the ocean. It could happen while crossing time zones east-to-west, but crossing the International Date Line west-to-east makes more of an interesting thought experiment.
Yes, I've given this silly joke scenario way more thought than it really deserves. :-)
hdjrudni [3 hidden]5 mins ago
Isn't that precisely the same?
Doesn't even have to be the International Date line, any two timezones work.
rmunn [3 hidden]5 mins ago
Yes, it's the same, the IDL just makes it easier for it to work, as otherwise the babies have to be born on either side of midnight while crossing the time zone line. With the IDL the birth time could be almost any time of day except for crossing over midnight and the joke would work.
whiskey-one [3 hidden]5 mins ago
A reminder associated with the birthday can and should be changed if I change time zones. But the birthday date didn’t change so it shouldn’t move to a different day.
skissane [3 hidden]5 mins ago
> But the birthday date didn’t change so it shouldn’t move to a different day.
But it does. My brother moved to the US for a few years. So we’d send him birthday wishes on the day of his birthday (Australia time), and he’d get them the day before his birthday (his time). Now he’s moved back to Australia, the same thing happens in reverse-he gets birthday wishes from his American friends the day after his birthday.
My wife has lots of American friends on Facebook (none of whom she knows personally, all people she used to play Farmville with)-and she has them wishing her a happy birthday the day after her birthday too. Maybe she’s doing the same to them in reverse.
thayne [3 hidden]5 mins ago
But using UTC doesn't solve that, unless the recipient of the birthday wishes is close to the prime meridian.
teiferer [3 hidden]5 mins ago
> sacrificed to the altar of "web compatibility."
What should they have done instead? Force everybody to detect browser versions and branch based on that, like in the olden days of IE5?
(Serious question, maybe I'm overlooking some smart trick.)
tshaddox [3 hidden]5 mins ago
I agree with the "don't break the web" design principle, but I sometimes disagree with precisely where TC39 draws the line. There is obviously a cost to breaking old, unchanging websites. But there's also a cost to allowing old, unchanging websites to hold the entire web hostage. Balancing those costs is a subjective matter.
As far as I know, TC39 doesn't have any clear guidelines about how many websites or how many users must be affected in order to reject a proposed change to JavaScript behavior. Clearly there are breaking changes that are so insignificant that TC39 should ignore them (imagine a website with some JavaScript that simply iterates over every built-in API and crashes if any of them ever change).
marcosdumay [3 hidden]5 mins ago
Browsers should version their languages. They should say "if you use <html version="5.2"> or bigger, this is the behavior".
Somehow, the standard groups decided to remove the versioning that was there.
cogman10 [3 hidden]5 mins ago
The decided not to have it there because they didn't like the idea of maintaining version 4.0 forever in their engines.
That's basically why they never did anything like "use strict" again.
IMO, that's a bad choice. Giving yourself the ability to have new behavior and features based on a version is pretty natural and how most programming languages evolve. Having perpetual backwards and fowards compatibility at all times is both hard to maintain and makes it really hard to fix old mistakes.
The only other reason they might have chosen this route is because it's pretty hard to integrate the notion of compatibility levels into minifiers.
mejutoco [3 hidden]5 mins ago
Have an optional parameter to opt in to the old behaviour and keep the new correct behaviour the default (without the parameter) seems like a decent choice.
stevula [3 hidden]5 mins ago
To preserve backwards compatibility and not require all those old sites to update, the legacy behavior would have to be the default, with opt-in for the new behavior.
mejutoco [3 hidden]5 mins ago
That is the opposite approach. Also an option. One could also deprecate the call without parameter and force always a parameter with which behaviour. The deprecation could last enough time that those websites would have been rewritten multiple times ;)
sfink [3 hidden]5 mins ago
The control interface burned into your hardware device will not have been rewritten. And it's not like you can have a flag day where everyone switches over, so the lifespan of those hardware devices isn't that relevant.
Backwards compatibility is a large part of the point of the Web.
You could version everything at whatever granularity you like, but over time that accumulates ("bug 3718938: JS gen24 code incorrectly handles Date math as if it were gen25-34", not to mention libraries that handle some versions but not others and then implicitly pass their expectations around via the objects they create so your dependency resolver has to look at the cross product of versions from all your depencies...)
mejutoco [3 hidden]5 mins ago
There is no free lunch. A deprecation warning lasting a decade before erroring will break less that some css boxing models and strict mode in many browsers.
new Date("not a date")
1) Invalid Date
2) undefined
3) Throws an error
4) null
There's literally no way of guessing this crap. It's all random.
dvt [3 hidden]5 mins ago
I had no idea we even had an `Invalid Date` object, that's legitimately insane. Some other fun ones:
new Date(Math.E)
new Date(-1)
are both valid dates lol.
winstonp [3 hidden]5 mins ago
the new Date() constructor is an amalgamation of like 5 different specs, and unless the input matches one of them, which one kicks in is up to the implementer's choice
marcosdumay [3 hidden]5 mins ago
The choice here is really surprising. I was half-expecting NaN, that you omitted.
Is there any other instance of the standard JS library returning an error object instead of throwing one? I can't think of any.
jazzyjackson [3 hidden]5 mins ago
I think NaN itself is a bit of an error object, especially in how it's passed through subsequent math functions, which is a different choice than throwing up.
But besides that I think you're right, Invalid Date is pretty weird and I somehow never ran into it.
One consequence is you can still call Date methods on the invalid date object and then you get NaN from the numeric results.
WorldMaker [3 hidden]5 mins ago
The fun trick is that Invalid Date is still a Date:
> let invalid = new Date('not a date')
> invalid
Invalid Date
> invalid instanceof Date
true
You were half-correct on expecting NaN, it's the low level storage of Invalid Date:
> invalid.getTime()
NaN
Invalid Date is just a Date with the "Unix epoch timestamp" of NaN. It also follows NaN comparison logic:
> invalid === new Date(NaN)
false
It's an interesting curio directly related to NaN.
tyilo [3 hidden]5 mins ago
> Invalid Date is just a Date with the "Unix epoch timestamp" of NaN. It also follows NaN comparison logic:
>
> > invalid === new Date(NaN)
> false
This is just because a JS Date is an object and have nothing to do with the inner representation.
> new Date(0) === new Date(0)
false
cush [3 hidden]5 mins ago
Maggie is a killer dev. Momentjs probably saved humanity millions of hours of collective coding and debugging
netghost [3 hidden]5 mins ago
If this is comedy, sign me up for tragedy.
This feels like something that must be the root of innumerable small and easily overlooked bugs out there.
tshaddox [3 hidden]5 mins ago
It's a common source of off-by-one date formatting bugs in client-rendered web apps, particularly ones that pass around "YYYY-MM-DD" date strings (common for OpenAPI JSON APIs).
const dateStringFromApiResponse = "2026-01-12";
const date = new Date(dateStringFromApiResponse);
const formatter = new Intl.DateTimeFormat('en-US', { dateStyle: 'long' });
formatter.format(new Date("2026-01-12"));
// 'January 11, 2026'
jazzyjackson [3 hidden]5 mins ago
I'm having flashbacks to writing Power Automate expressions to reconcile Dates passed from Outlook metadata to Excel
Basically just extracting numbers from string index or regex and rearranging them to a string Excel would recognize
sholladay [3 hidden]5 mins ago
Personally, I like that UTC is the default time zone. Processing of dates should happen in a standardized time zone. It’s only when you want to display it that the date should become local.
sfink [3 hidden]5 mins ago
UTC is a fine default time zone, but that doesn't matter here.
A datetime with a timezone and a datetime without one are two different things, both of them useful. My birthday does not have a time zone. My deadline does.
The company deadline for getting some document returned? It might or might not, that's policy.
Poetically: we are born free of time zones. We die bound to one.
throwaway290 [3 hidden]5 mins ago
> My birthday does not have a time zone. My deadline does.
That seems subjective
lysium [3 hidden]5 mins ago
This will result in incorrect behavior when, between converting to UTC and back to the original timezone, the timezone database has changed, which happens more often than you think.
procaryote [3 hidden]5 mins ago
There's a lot wrong with Javascript's Date, but the fact that it's an object is is not really in the top 10.
Would it have been nice if the Date object had been immutable? Sure, but the fact that changing the mutable object does indeed change the object shouldn't be a shock
chowells [3 hidden]5 mins ago
It's definitely a shock when something else changes the date object you've been holding on to. The problem with mutable values has never been when you (that is, the local context) change them. It's always that you can't trust that nothing else (some very non-local code) does.
petesergeant [3 hidden]5 mins ago
That’s how every other object works, why would that be surprising?
arthens [3 hidden]5 mins ago
That's a fair observation, and yet anecdotally I agree with the parent comment. In my career I fixed quite a few bugs about dates being passed around and unexpectedly modified, while I struggle to remember the same problem with objects in general (could be a case of selective memory).
If I had the guess, I'd say it's a combination of:
- the difference between the mental model and the implementation. Dates are objects but "feel" like values: dates are parsed from a single value, and when stored/printed they collapse back to a single value (as opposed to custom objects which are generally a bag of properties, and when printed/stored they still look like an object)
- most common date operations causes the original date object to be mutated, which implicitly causes developers to mutate the passed value even if that's not what they explicitly meant
So the default combination is a calling code that expects date to be treated as a value, and the called code accidentally mutating the data because it's convenient to do so. If anything then causes the original value to be saved back in the db, the data gets corrupted.
Most experienced developers will remember to make a copy of the date object both in the calling code and in the receiving code, but the default remains dangerously easy to get wrong.
kortilla [3 hidden]5 mins ago
The lack of const means having objects as arguments is pretty dangerous
ruszki [3 hidden]5 mins ago
What parent commenter meant was language level support of immutable objects. There is const, in for example JavaScript, but it supports only immutability of variables, not objects themselves. That later one is possible in C++ for example, where const can be used for both. Of course, it’s still possible to fake immutability with interfaces in some languages, or have a real one forced by implementation (like with Temporals), but it’s much nicer to have an indicator forcing that.
I would like to add, that both variable and object immutability should be the default, and mutability should have a keyword, not other way around how in C++ and Java.
LegionMammal978 [3 hidden]5 mins ago
I do find it annoying how the Temporal API, just like nearly all other datetime APIs, has 0 support for querying leap-second information in any shape or form. Suggested workarounds like temporal-tai all require plugging in a leap-second file and keeping it updated, which is especially painful for client-side JS, where you can't just download a leap-second file from someone else's site thanks to the SOP. Meanwhile, browsers update on a cadence more than sufficient to keep an up-to-date copy, but the datetime APIs refuse to expose leap-second info because they're too committed to "only UTC is in-scope for this project".
(The context is that I want to write some JS tools for astronomical calculations, but UTC conversions need leap-second info, so this trend makes it impossible to write something that Just Works™.)
schiffern [3 hidden]5 mins ago
>only UTC is in-scope for this project
>tools for astronomical calculations
Pity, since UTC is objectively the wrong time for astronomical calculations. Among other problems, UTC runs slightly slower or faster depending on how far the Earth is from the Sun. UTC does not run uniformly (outside of Earth-at-sealevel), instead the length of 1 second will slightly grow or shrink depending on the current configuration of the Solar system.
As you allude to, the correct time scale for this purpose would be TBD (aka Barycentric Dynamical Time), which applies relativistic corrections to act like the atomic clock is fixed at the barycentre of the Solar system. This is the only clock that actually runs "smoothly" for the purposes of astronomical calculations.
> Among other problems, UTC runs slightly slower or faster depending on how far the Earth is from the Sun. UTC does not run uniformly (apart from Earth-at-sealevel), instead the length of 1 second will slightly grow or shrink depending on the current configuration of the Solar system.
That is completely wrong. UTC seconds are exactly SI seconds, which are all the same uniform length (defined by quorum of atomic clocks).
nightpool [3 hidden]5 mins ago
> where you can't just download a leap-second file from someone else's site thanks to the SOP
WDYM by this? Why does the SOP prevent a website from hosting a leap seconds file? All they need to do is set Access-Control-Allow-Origin to allow websites to access it. Or provide it as a JS file—in which case no headers are necessary at all. All the SOP prevents is you hotlinking someone else's leap-seconds file and using their bandwidth without their opt-in.
> Meanwhile, browsers update on a cadence more than sufficient to keep an up-to-date copy
Is this true? I don't know any browser right now that ships with a copy of a leapseconds data file. Adding such a data file and keeping it up to date would probably be a pretty non-trivial task for new browser developers—just for something the browser will never end up using itself. It's not like the ICU/CLDR files where browsers are going to need them anyway for rendering their own user-interface components.
LegionMammal978 [3 hidden]5 mins ago
> All they need to do is set Access-Control-Allow-Origin to allow websites to access it. All the SOP prevents is you hotlinking someone else's leap-seconds file and using their bandwidth without their opt-in.
They can, but the major providers (read: the ones I would trust to update it) don't. The IERS doesn't [0], the USNO doesn't [1], IANA doesn't [2], and NIST uses FTP [3]. Keep in mind that these files are constantly being downloaded by various clients for NTP and whatnot, it's not like these providers want to restrict public access, they just don't bother to set the header that would allow JS requests.
> Is this true? I don't know any browser right now that ships with a copy of a leapseconds data file.
From ECMA-262:
> It is required for time zone aware implementations (and recommended for all others) to use the time zone information of the IANA Time Zone Database https://www.iana.org/time-zones/.
Any browser that ships with a copy of tzdb, or knows where to find a copy from the OS, should have access to its leapseconds file. Unless you mean that all of them go solely through ICU and its data files? Which I suppose could be an obstacle unless ICU were to start exposing them.
Could you put some kind of CORS proxy in front of those URLs? (I know it sucks that you have to do this at all, but c'est la vie.)
You could even write a Cloudflare Worker or a Val on val.town to do that, and add a bit of caching on top so you don't hit your providers too often.
burntsushi [3 hidden]5 mins ago
> but the datetime APIs refuse to expose leap-second info because they're too committed to "only UTC is in-scope for this project".
This doesn't make sense on at least two different levels.
First, pedantically, the definition of UTC as a time scale is that it includes leap seconds. So if you're committed to UTC, then you're supporting leap seconds.
Second, and to more broadly address your point, you should say, "they're too committed to 'only the POSIX time scale is in-scope for this project.'" That more accurately captures the status quo and also intimates the problem: aside from specialty applications, basically everything is built on POSIX time, which specifically ignores the existence of leap seconds.
LegionMammal978 [3 hidden]5 mins ago
Sure, but my gripe isn't even that we ought to change the "POSIX time by default" status quo (the ship has long sailed that everyone counts durations by 'calendar seconds'), it's that the underlying libraries don't even provide enough information for "specialty applications" to reliably correct for it, short of perpetually updating it themselves.
burntsushi [3 hidden]5 mins ago
Why should they though? To me it seems like a niche of a niche. I think there is plenty of room for scientific datetime libraries to service this need in a way that is likely better than what a general purpose datetime library would provide. (And indeed, there are many of them.)
I say this as someone who had leap second support working in a pre-release version of Jiff[1] (including reading from leapsecond tzdb data) but ripped it out for reasons.[2]
That's part of it: If I were writing a standalone program that could extract info from tzdb or whatever, I'd happily jump through those hoops, and not bother anyone else's libraries. I don't really care about the ergonomics. But for JS scripts in particular, there is no information available that is not provided by either the browser APIs or someone's server. And such servers are not in great supply.
kortilla [3 hidden]5 mins ago
It’s not “niche” if you do things synchronized to GPS timestamps. (i.e. a significant portion of telecom, a bunch of electrical grid stuff, etc).
Anything using GPS as lock references to synchronize stuff that needs to be aligned to the millisecond absolutely cannot tolerate stuff like “the leap second smear”.
hgs3 [3 hidden]5 mins ago
> like nearly all other datetime APIs, has 0 support for querying leap-second information
That's probably because you only need leap second accuracy in niche use cases, like astronomy or GPS. In JavaScript specifically, that kind of accuracy isn't needed for 99% of client-side use cases. Most date-time libraries work with POSIX time which assumes 86,400 seconds each day.
mr_toad [3 hidden]5 mins ago
Can’t you just mirror the data? You could even embed it in the javascript file itself.
paulddraper [3 hidden]5 mins ago
> I do find it annoying how the Temporal API, just like nearly all other datetime APIs, has 0 support for querying leap-second information in any shape or form.
That’s because human time keeping doesn’t use leap seconds.
irjustin [3 hidden]5 mins ago
Late to the party, I really wish everyone would copy Rails + Ruby, but specifically it's Rails additions.
2 things it got right:
1. Like the article a great API - Time.current.in_time_zone('America/Los_Angeles') + 3.days - 4.months + 1.hour
2. Rails overloads Ruby's core library Time. You're in 1 object the whole time no swap/wondering.
In the py world, pendulum is close but just like the article, it's cumbersome as it's still a separate obj (i.e. Temporal vs Date) and so you need to "figure out" what you have to manipulate or need to cast it first.
Overloading the core libs is dangerous for a whole host of reasons but for the end developer it's a pleasure to use.
If we could just do `new Date().add({ days: 1})` it would be so easier.
happytoexplain [3 hidden]5 mins ago
>3.days - 4.months + 1.hour
Is this what it looks like? A specific concept like time units being defined as members of more general types like numbers? I.e. if I type `1.` to get auto-complete, am I going to see days, and all the rest, as options?? That API design pattern would be a nightmare!
greiskul [3 hidden]5 mins ago
In Ruby, I assume this is done by monkey patching, so yes, it would have all the issues you mention and fear.
In more modern languages like Kotlin, there is a notion of extension methods and properties, where you would be able to write a library that allows this syntax, but the .days property would only be accessible in files where you have explicitly imported it (so basically a synthetic sugar for a static function call).
pprotas [3 hidden]5 mins ago
Here is the neat part about Ruby, your autocomplete barely works and your IDE can only guess what you want, instead of relying on a good language service…
publicdebates [3 hidden]5 mins ago
> 3.days - 4.months + 1.hour
How is that a good thing?
> Rails overloads Ruby's core library Time. You're in 1 object the whole time regardless of what you do.
How is that a good thing?
shermantanktop [3 hidden]5 mins ago
When what you have is a pickaxe, everything looks like a rail...
daveoc64 [3 hidden]5 mins ago
I'm really surprised at how Temporal is only just rolling out in Chrome stable.
I would have hoped it'd be ready for wider use by now.
We’ve been loving using it in our Deno servers since last year. It’s been frustrating that we haven’t been able to upgrade our web client date logic yet, since even though Firefox has supported Temporal for a while, Chrome have really dragged their feet
ZeWaka [3 hidden]5 mins ago
All the chromiums are scheduled for this week. Still TP for WebKit.
munificent [3 hidden]5 mins ago
> When an immutable value is assigned to a variable, the JavaScript engine creates a copy of that value and stores the copy in memory
Not exactly. The language doesn't specify whether the value is copied or not and, precisely because values are immutable, there's no way for a user to tell if it was or wasn't.
For example, strings are also immutable value types, but you can be certain that no JS engine is fully copying the entire string every time you assign one to a variable or pass it to a parameter.
How is it compared to moment and especially luxon?
MrJohz [3 hidden]5 mins ago
It is a lot more complex than moment, but only because there's a lot of inherent complexity to dates and times that moment just doesn't deal with. So you need to be explicit about whether you're dealing with dates, times, or datetime objects, whether or not the object you're working with has a timezone, etc. Where moment is generally designed to have a convenient API, Temporal is designed to have a correct API.
socalgal2 [3 hidden]5 mins ago
Didn't moment basically say in so many words, use Temporal?
WorldMaker [3 hidden]5 mins ago
Moment said many years ago "use Luxon" [1]. Luxon is not yet at the "use Temporal" stage [2].
It’s a web standard api and very small weight. Highly recommend.
tensegrist [3 hidden]5 mins ago
typo:
// A numeric string between 32 and 49 is assumed to be in the 2000s:
console.log( new Date( "49" ) );
// Result: Date Fri Jan 01 2049 00:00:00 GMT-0500 (Eastern Standard Time)
// A numeric string between 33 and 99 is assumed to be in the 1900s:
console.log( new Date( "99" ) );
// Result: Date Fri Jan 01 1999 00:00:00 GMT-0500 (Eastern Standard Time)
the second interval should start at 50, not 33
noduerme [3 hidden]5 mins ago
I use Moment.
And a few years later, I'm still using Moment.
And now I'm still using Moment.
And now...
xeckr [3 hidden]5 mins ago
I suspect that the arrival of ChatGPT caused traffic to the MDN Date API documentation to go down by at least half.
qsort [3 hidden]5 mins ago
To be fair it's exactly the type of stuff I'd be glad if I never have to think about again.
ivanjermakov [3 hidden]5 mins ago
Go down by half of user traffic, go up 10x of crawler traffic.
thoughtpalette [3 hidden]5 mins ago
Built a scheduler with pretty much all my moment/moment-tz questions answered through ChatGPT. One of the things it excels at, crawling long lived API documentation, answers, etc.
themafia [3 hidden]5 mins ago
The Date API is fine and relatively normalized. Once you understand it it's very easy to work with. It's biggest problem is that it simply does not support timezones, which is the main reason to use Temporal.
LtdJorge [3 hidden]5 mins ago
The Date API is horrible
themafia [3 hidden]5 mins ago
Yea, that's understood to be the opinion, blandly repeating it adds little to the discussion.
It's simple. In it's simplicity it left many features on the floor. I just can't connect with the idea that someone would need to constantly be on MDN in order to work with it. It's not so horrible that it defies logic.
acdha [3 hidden]5 mins ago
It’s not simple, though. Simple would be something like an object wrapping YYYY-MM-DD, like a COBOL programmer in the 1950s would’ve used. Instead, people have made thousands of variations of bugs around the complexity even basic usage forces you to internalize like the month number being zero-based while the year is 1900-based but the day of the month is 1-based following standard usage.
winstonp [3 hidden]5 mins ago
yep. i had a hell of a time building a scheduling system for a business that worked across timezones with the date API
Aardwolf [3 hidden]5 mins ago
Checking its API, I'm surprised that Temporal.Duration has a constructor with many parameters for years, months, days, ... all the way to nanoseconds, while Temporal.Instant has no way at all to create it given a current year/month/day, only from unix timestamp equivalents (or strings)
That seems to be functionality you'd want to have? Or is the intention you convert your numbers to string first and then back to a Temporal.Instant?
tshaddox [3 hidden]5 mins ago
It's perfectly reasonable to default seconds, minutes, hours, etc. to zero in the Duration constructor. But for Instant, it doesn't make sense to default those to zero unless you specify time zone offset.
And indeed, the static method Instant.from does accept an RFC 9557 string, which requires a 2-digit hour and a time zone offset, but can omit minutes and seconds:
Temporal.Instant.from("2026-01-12T00+08:00")
Macha [3 hidden]5 mins ago
I guess they don’t want people getting confused between local and UTC values for the fields in the constructor (especially as if it took local values it would need to handle DST transitions)
sheept [3 hidden]5 mins ago
it's because a year/month/date isn't enough to uniquely identify an instant in time. you can create a Temporal.PlainDate(Time) with those values though, then convert to the other types depending on what you need and it needs (e.g. time zone)
austin-cheney [3 hidden]5 mins ago
The article is super weird. It never mentions Date.now(). It dances around the subject and exhaustively mentions the equivalent convention for Temporal.
If you want Date to act like Temporal then only use Date.now() as your starting point. It generates the number of milliseconds since 1 Jan 1970. That means the starting output is a number type in integer form. It does not represent a static value, but rather the distance between now and some universal point in the past, a relationship. Yes, Temporal is a more friendly API, but the primary design goal is to represent time as a relational factor.
Then you can format the Date.now() number it into whatever other format you want.
ffsm8 [3 hidden]5 mins ago
the article has examples of unexpected behavior with timestamps too, so... How do you covert to your desired format without going through Date? Please don't say date-fns
rjrjrjrj [3 hidden]5 mins ago
Good article, but “Java deprecated their Date way back in 1997” is not exactly true. They deprecated a lot of methods and constructors in JDK1.1 when Calendar was introduced, but the class itself was never deprecated and it was the preferred way to represent a point in time until the “modern” approach was provided in java.time in JDK8 (c2014)
shellac [3 hidden]5 mins ago
Not exactly true, but they deprecated absolutely everything that made it a date. It expresses deep regret in the medium of annotations:
(I can't find the 1.1 docs, but they were the same)
It's one of my favourite examples of how languages pretty much always get date and time hopelessly wrong initially. Java now has one of the best temporal APIs.
rjrjrjrj [3 hidden]5 mins ago
Yeah, it effectively became a typed wrapper of a long epoch millis value. Generally treated as immutable by convention in my experience, although of course it technically wasn't as the setters were never removed.
It was hopelessly wrong initially, and got even worse when they added the horrible sql Date/Timestamp/etc classes.
With java.time though, it is the gold standard as far as I've seen.
cogman10 [3 hidden]5 mins ago
Java's time and duration representations, heavily based on Joda, should be the standard that every language works towards.
It's just about perfect in every way. It makes it easy to do the right thing and it's very pleasant to read.
The current global availability of native Temporal is 1.81%. For context, IE11(!) has a higher global usage than Temporal has native support. For my organization, this likely means we're years from being able to use Temporal in production, because getting the polyfills approved is such a hassle.
Keep in mind that even as of December last year, Chrome didn't ship with it yet (i.e. support is less than one month old). Safari still does not.
senfiaj [3 hidden]5 mins ago
Chrome will ship in 144. It's about to release.
winstonp [3 hidden]5 mins ago
Once Chrome does, for many devs, you can simply enforce a version check and say "please use latest Chrome" and be done with it.
promiseofbeans [3 hidden]5 mins ago
Please never do version checks. Test for the existence of the exact features/methods you need instead - this is trivial in JS: if(Temporal)
Checking against version numbers helps cement existing browser monopolies, makes it difficult for new browsers to view websites (even if the browser correctly implements every feature), and encourages everyone to spoof version numbers / browser names which leads to them becoming a less and less useful signal. See any browser’s User-Agent string for an example of this
themafia [3 hidden]5 mins ago
Thankfully temporal-polyfill only depends on temporal-spec. It was pretty easy to get that through.
whiterook6 [3 hidden]5 mins ago
So, hold on--the author's soul-breaking complaint isn't all of the "quirks" and inconsistencies with the Date functions, but rather the fact that it's an object? Specifically, an object with mutable properties in a language when all objects have mutable properties?
I mean, the author's conclusion is correct. But I disagree with the rationale. It's like hating an evil dictatorship because they use the wrong font in their propaganda.
schiffern [3 hidden]5 mins ago
>It wholesale does not understand the concept of daylight savings time
While we're nitpicking (which I wholly support, by the way) it's "daylight saving time."
related: i had to jump through the Date hoops recently (again) when rewriting uPlot's DST and timezone handling, but i'm pretty happy with the result that avoided much complexity, performance loss, and adding a dependency: https://github.com/leeoniya/uPlot/pull/1072
If only Safari had support for Temporal... maybe next year...
pmarreck [3 hidden]5 mins ago
I actually had no idea javascript Date was this bad until now.
acdha [3 hidden]5 mins ago
What’s really sad is that this was obvious in 1995. If they’d taken a slightly longer time back then, millions of developers would have avoided tripping over those unnecessary quirks.
atoav [3 hidden]5 mins ago
If you ever find yourself in the situation where you have to decide whether 99 parses to year 1999 and what to do with 100 and where to draw the line between parsing the 90s and current years, you should probably pause, reath in andaout and take a long walk instead. And after you return you should scrap the whole thing and go back to the drawing board.
Implementing such a feature has not only no value, it has negative value. When you program libraries or interfaces you ahould think aboit how people will use it 95% of the time and mane that usecase as simple, predictable and free of potential footguns as possible. This is the opposite of that. It feels like something 15 year old me would have programmed after reading the first book on PHP and not something anybosy with any experience could have thought to be a good thing.
moralestapia [3 hidden]5 mins ago
Not yet, adoption is kind of poor atm.
This is not to detract from the quality of the article which is a top-notch introduction to this new API.
ckocagil [3 hidden]5 mins ago
Late by a decade or more (JSR310 was released in 2014), but still a good development. I've tried convincing colleagues to use js-joda in the past but they thought they were keeping it simple by sticking to moment.js. They weren't.
Anyone have links that indicate when Safari might have it?
promiseofbeans [3 hidden]5 mins ago
The JSC people have been relatively involved as the spec was developed, and they have it behind a flag in their TP builds . It’ll probably ship in Safari once it ships in Chrome so that their users don’t complain about broken websites
LoganDark [3 hidden]5 mins ago
Is Temporal even in though? Last I checked (last year or so), I had to use some bleeding edge version of Firefox to get it, and absolutely nothing else had it. I do agree though it's lovely, and I'd love to see native support for it.
Nope. Only Firefox and Chrome have it, in their latest versions. No Safari or Edge support yet. So this article is a bit premature (unless you use the polyfill.)
zvqcMMV6Zcr [3 hidden]5 mins ago
I am not sure if I like mixing value and formatting in single object. On other hand anything will be an improvement compared to that terrible old API.
happytoexplain [3 hidden]5 mins ago
Temporal objects do not store formatting information. Unless you mean e.g. dropping the time, using a different time zone, etc - but those aren't formatting changes, they logically change the semantics of the data. Just like `myInt += 1` is not changing the "formatting" of `myInt`.
Remember: Date and Temporal objects are logically different things. A Date represents an absolute point in time (a timestamp), while a Temporal object represents a human time (calendar date, clock time, time zone). The fact that Dates are used to represent human time for lack of a better structure is the entire problem statement - the hole that all these other APIs like Temporal try to fill in.
zvqcMMV6Zcr [3 hidden]5 mins ago
I just groked it before and thought "plain" in `Temporal.PlainDateTime` indicates some specific format instead of just being zoneless. It is actually always using ISO8601 fur build in toString conversions, so I don't really have anything to complain about.
sublinear [3 hidden]5 mins ago
> My complaint is about more than parsing or syntax or “developer ergonomics” ... My problem with Date is that using it means deviating from the fundamental nature of time itself.
I don't really have a problem with the substance of this blog post. I have a problem with this exaggerated writing style. It means deviating from the fundamental purpose of writing itself!
I had to scroll all the way to the end to find the actual point, and it was underwhelming.
> Unlike Date, the methods we use to interact with a Temporal object result in new Temporal objects, rather than requiring us to use them in the context of a new instance
Bro, just be honest. This entire blog post was totally about developer ergonomics and that's okay. We all hate the way Date works in javascript.
happytoexplain [3 hidden]5 mins ago
It's not an exaggeration - you're used to dramatic phrases that use similar wording ("fundamental nature of time itself"), but in this case it's a regular old literally-true statement. Date is used to represent two things: Timestamps and human times (date, time, tz). But it only actually represents the former. Using it to represent the latter is a hack we simply put up with.
sfink [3 hidden]5 mins ago
Pedantically, Temporal also deviates from the fundamental nature of time itself. Temporal.Instant? In which accelerating frame of reference? It supports equality, which is a nonsense concept.
jdonaldson [3 hidden]5 mins ago
[flagged]
DarkNova6 [3 hidden]5 mins ago
What’s the superior alternative and in which domains?
artursapek [3 hidden]5 mins ago
bro these ads I can't
TZubiri [3 hidden]5 mins ago
Yes, you should use shiny new library instead of the glitchy javascript standard..
Unless you want your website to run in browsers older than a year
Maybe in 10 years we can start using the shiny new thing?
What's actually happening here is a comedy of errors. JavaScript is interpreting that particular string format ("YYYY-MM-DD") as an ISO 8601 date-only form. ISO 8601 specifies that if no time zone designator is provided, the time is assumed to be in local time. The ES5 spec authors intended to match ISO 8601 behavior, but somehow accidentally changed this to 'The value of an absent time zone offset is “Z”' (UTC).
Years later, they had realized their mistakes, and attempted to correct it in ES2015. And you can probably predict what happened. When browsers shipped the correct behavior, they got too many reports about websites which were relying on the previous incorrect behavior. So it got completely rolled back, sacrificed to the altar of "web compatibility."
For more info, see the "Broken Parser" section towards the bottom of this article:
https://maggiepint.com/2017/04/11/fixing-javascript-date-web...
This is why I don't understand the lack of directives.
'use strict'; at the top of a file was ubiquitous for a long time and it worked. It didn't force rolling back incompatibilities, it let you opt into a stricter parsing of JavaScript.
It would have been nice for other wide changes like this to have like a 'strict datetime'; directive which would opt you into using this corrected behavior.
They couldn't and shouldn't do this sort of thing for all changes, but for really major changes to the platform this would be an improvement.
Or they could go all in on internal modules, like how you can import `node:fs` now. They could include corrected versions of globals like
`import Date from 'browser:date';`
has corrected behavior, for example
Internal modules would be handy in theory to maybe keep from having to dig through a thesaurus every time browsers decide to add a new, stricter version of an older API. Internal modules have even been proposed to TC-39 as a recommended way to continue to expand the JS API. Last I checked on that proposal it was stuck behind several concerns including:
1. Feature detection: detecting if Temporal available is as easy as `if ('Temporal' in globalThis) {}`, but detecting if a module import is missing is a bit harder. Right now the standard is that loading a module fails with an Error if one of its imports fails. You can work around that by doing a dynamic import inside a try/catch, but that's a lot of extra boilerplate compared to `const thingINeed = 'someApi' in globalThis ? someApi() : someApiPolyfill()`. I've seen multiple proposals on that front from extensions to import maps and `with { }` options on the import itself.
2. Bikeshedding (and lots of it): defining a URI scheme like `browser:` or `standard:` takes a bunch of thought on how you expand it. If it is just `browser:some-api` you run the risk of eventually polluting all the easy names in the exact way people worry about the risk of over-polluting `globalThis` (and in the way that it can be weirdly hard to find an available one-word name on npm), you've just moved the naming problem from one place to the other. On the other side, if you go down the road of something like `es-standard:https://tc39.es/ecma262/2025/v1/final-draft/Temporal`, even (especially) assuming users would mostly importmap that to something shorter you've recreated XMLNS URIs in a funny new hat and people who use JS all certainly have plenty of opinions on XMLNS URIs, many are very vocal in their hatred of it, but also they came out of a strong backwards incompatibility fixing desire exactly like this. (As they say time is a flat circle.)
This. Don't break old code, just provide new best practices.
Update linters (or ideally first class language rules, like in Rust's "edition"s), to gradually kill off old behavior. Without having to do a decade long Python 2 -> 3 migration.
Temporal is nice. It learned from the many failures and dead bodies that came before it. And it had lots of good implementations to look at: Joda Time, Chrono, etc.
There are so many (in hindsight bad) design choices and implementation accidents that currently exist in perpetuity because of backwards compatibility; the web would really benefit if every now and then we could shed old baggage.
That would be ugly, because you'd want some parts of your program (eg libraries) to use the old behaviour, and other parts might want the new behaviour. How would you minify multiple modules together if they all expect different behaviour from the standard library?
In my opinion the right way to do this is to have multiple constructors (as Obj-C, swift, C and rust all do). Eg:
The big downside of this is that its tricky to keep track of which fields and functions people should really stop using in modern javascript. It'd be nice if there was a way to enable more shouty warnings during development for deprecated JS features.How does it get out of hand?
FWIW, I just do `use v5.32;` or similar to opt-in to everything from that version.
https://perldoc.perl.org/functions/use#use-VERSION
Of course, if you instead want to pick-and-choose features, then I can see the list growing large.
Sometimes a date is just a date. Your birthday is on a date, it doesn't shift by x hours because you moved to another state.
The old Outlook marked birthdays as all-day events, but stored the value with time-zone, meaning all birthdays of people whose birthday I stored in Belgium were now shifted as I moved to California...
After having a bunch of problems with dealing with Dates coded as DateTime, I've begun coding dates as a Date primitive, and wrote functions for calculation between dates ensuring that timezone never creeps its way into it. If there is ever a DateTime string in a Date column in the database, it's impossible to know what the date was supposed to be unless you know you normalized it at some point on the way up.
Then I found that a lot of DatePicker libraries, despite being in "DATE" picker mode, will still append a local timezone to its value. So I had to write a sanitizer for stripping out the TZ before sending up to the server.
That said, I am pretty excited about Temporal, it'll still make other things easier.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
E.G. in a conversation "Lets open the shop at 9am every day that it isn't closed." Is a fairly simple recurrence, with some exceptions*. If timezones change the scheduled time remains evaluated again on each day.
I'm not necessarily defending the implementation, just pointing out another way in which time is irreducibly ambiguous and cursed.
The riddle explanation was something like: A baby is born in New York City at 12:15 AM on January 1. Thirty minutes later, another baby is born in Los Angeles, where the local time is 9:45 PM on December 31. Although the New York baby is actually older by 30 minutes, the calendar dates make it appear as though the Los Angeles baby was born first.
The timezones thing, of course, is just a way to have the younger twin be born "a year ahead" of the older twin by having their births be in two different timezones. Only practical way that would happen would be aboard a ship, because 1) babies born aboard an airplane would probably end up using the time zone of departure or of destination for their birth, and so twins would not be counted as being born in different time zones. And 2) any land-based transportation such as a car or a train would likely pull over (or in the case of a train, let the pregnant woman off at the nearest station) so that the woman giving birth doesn't have to do so in a moving vehicle. So a ship is the only moving vehicle where this kind of thing could likely happen, as there's no option of getting off in the middle of the ocean. It could happen while crossing time zones east-to-west, but crossing the International Date Line west-to-east makes more of an interesting thought experiment.
Yes, I've given this silly joke scenario way more thought than it really deserves. :-)
Doesn't even have to be the International Date line, any two timezones work.
But it does. My brother moved to the US for a few years. So we’d send him birthday wishes on the day of his birthday (Australia time), and he’d get them the day before his birthday (his time). Now he’s moved back to Australia, the same thing happens in reverse-he gets birthday wishes from his American friends the day after his birthday.
My wife has lots of American friends on Facebook (none of whom she knows personally, all people she used to play Farmville with)-and she has them wishing her a happy birthday the day after her birthday too. Maybe she’s doing the same to them in reverse.
What should they have done instead? Force everybody to detect browser versions and branch based on that, like in the olden days of IE5?
(Serious question, maybe I'm overlooking some smart trick.)
As far as I know, TC39 doesn't have any clear guidelines about how many websites or how many users must be affected in order to reject a proposed change to JavaScript behavior. Clearly there are breaking changes that are so insignificant that TC39 should ignore them (imagine a website with some JavaScript that simply iterates over every built-in API and crashes if any of them ever change).
Somehow, the standard groups decided to remove the versioning that was there.
That's basically why they never did anything like "use strict" again.
IMO, that's a bad choice. Giving yourself the ability to have new behavior and features based on a version is pretty natural and how most programming languages evolve. Having perpetual backwards and fowards compatibility at all times is both hard to maintain and makes it really hard to fix old mistakes.
The only other reason they might have chosen this route is because it's pretty hard to integrate the notion of compatibility levels into minifiers.
Backwards compatibility is a large part of the point of the Web.
You could version everything at whatever granularity you like, but over time that accumulates ("bug 3718938: JS gen24 code incorrectly handles Date math as if it were gen25-34", not to mention libraries that handle some versions but not others and then implicitly pass their expectations around via the objects they create so your dependency resolver has to look at the cross product of versions from all your depencies...)
One can't fathom how weird JS Date can be.
Got to question 4 and gave up:
There's literally no way of guessing this crap. It's all random.Is there any other instance of the standard JS library returning an error object instead of throwing one? I can't think of any.
But besides that I think you're right, Invalid Date is pretty weird and I somehow never ran into it.
One consequence is you can still call Date methods on the invalid date object and then you get NaN from the numeric results.
This is just because a JS Date is an object and have nothing to do with the inner representation.
This feels like something that must be the root of innumerable small and easily overlooked bugs out there.
Basically just extracting numbers from string index or regex and rearranging them to a string Excel would recognize
A datetime with a timezone and a datetime without one are two different things, both of them useful. My birthday does not have a time zone. My deadline does.
The company deadline for getting some document returned? It might or might not, that's policy.
Poetically: we are born free of time zones. We die bound to one.
That seems subjective
Would it have been nice if the Date object had been immutable? Sure, but the fact that changing the mutable object does indeed change the object shouldn't be a shock
If I had the guess, I'd say it's a combination of:
- the difference between the mental model and the implementation. Dates are objects but "feel" like values: dates are parsed from a single value, and when stored/printed they collapse back to a single value (as opposed to custom objects which are generally a bag of properties, and when printed/stored they still look like an object)
- most common date operations causes the original date object to be mutated, which implicitly causes developers to mutate the passed value even if that's not what they explicitly meant
So the default combination is a calling code that expects date to be treated as a value, and the called code accidentally mutating the data because it's convenient to do so. If anything then causes the original value to be saved back in the db, the data gets corrupted.
Most experienced developers will remember to make a copy of the date object both in the calling code and in the receiving code, but the default remains dangerously easy to get wrong.
I would like to add, that both variable and object immutability should be the default, and mutability should have a keyword, not other way around how in C++ and Java.
(The context is that I want to write some JS tools for astronomical calculations, but UTC conversions need leap-second info, so this trend makes it impossible to write something that Just Works™.)
As you allude to, the correct time scale for this purpose would be TBD (aka Barycentric Dynamical Time), which applies relativistic corrections to act like the atomic clock is fixed at the barycentre of the Solar system. This is the only clock that actually runs "smoothly" for the purposes of astronomical calculations.
https://stjarnhimlen.se/comp/time.html
That is completely wrong. UTC seconds are exactly SI seconds, which are all the same uniform length (defined by quorum of atomic clocks).
WDYM by this? Why does the SOP prevent a website from hosting a leap seconds file? All they need to do is set Access-Control-Allow-Origin to allow websites to access it. Or provide it as a JS file—in which case no headers are necessary at all. All the SOP prevents is you hotlinking someone else's leap-seconds file and using their bandwidth without their opt-in.
> Meanwhile, browsers update on a cadence more than sufficient to keep an up-to-date copy
Is this true? I don't know any browser right now that ships with a copy of a leapseconds data file. Adding such a data file and keeping it up to date would probably be a pretty non-trivial task for new browser developers—just for something the browser will never end up using itself. It's not like the ICU/CLDR files where browsers are going to need them anyway for rendering their own user-interface components.
They can, but the major providers (read: the ones I would trust to update it) don't. The IERS doesn't [0], the USNO doesn't [1], IANA doesn't [2], and NIST uses FTP [3]. Keep in mind that these files are constantly being downloaded by various clients for NTP and whatnot, it's not like these providers want to restrict public access, they just don't bother to set the header that would allow JS requests.
> Is this true? I don't know any browser right now that ships with a copy of a leapseconds data file.
From ECMA-262:
> It is required for time zone aware implementations (and recommended for all others) to use the time zone information of the IANA Time Zone Database https://www.iana.org/time-zones/.
Any browser that ships with a copy of tzdb, or knows where to find a copy from the OS, should have access to its leapseconds file. Unless you mean that all of them go solely through ICU and its data files? Which I suppose could be an obstacle unless ICU were to start exposing them.
[0] https://hpiers.obspm.fr/iers/bul/bulc/ntp/leap-seconds.list
[1] https://maia.usno.navy.mil/ser7/tai-utc.dat
[2] https://data.iana.org/time-zones/tzdb/leap-seconds.list
[3] ftp://ftp.boulder.nist.gov/pub/time/leap-seconds.list
You could even write a Cloudflare Worker or a Val on val.town to do that, and add a bit of caching on top so you don't hit your providers too often.
This doesn't make sense on at least two different levels.
First, pedantically, the definition of UTC as a time scale is that it includes leap seconds. So if you're committed to UTC, then you're supporting leap seconds.
Second, and to more broadly address your point, you should say, "they're too committed to 'only the POSIX time scale is in-scope for this project.'" That more accurately captures the status quo and also intimates the problem: aside from specialty applications, basically everything is built on POSIX time, which specifically ignores the existence of leap seconds.
I say this as someone who had leap second support working in a pre-release version of Jiff[1] (including reading from leapsecond tzdb data) but ripped it out for reasons.[2]
[1]: https://github.com/BurntSushi/jiff
[2]: https://github.com/BurntSushi/jiff/issues/7
That's part of it: If I were writing a standalone program that could extract info from tzdb or whatever, I'd happily jump through those hoops, and not bother anyone else's libraries. I don't really care about the ergonomics. But for JS scripts in particular, there is no information available that is not provided by either the browser APIs or someone's server. And such servers are not in great supply.
Anything using GPS as lock references to synchronize stuff that needs to be aligned to the millisecond absolutely cannot tolerate stuff like “the leap second smear”.
That's probably because you only need leap second accuracy in niche use cases, like astronomy or GPS. In JavaScript specifically, that kind of accuracy isn't needed for 99% of client-side use cases. Most date-time libraries work with POSIX time which assumes 86,400 seconds each day.
That’s because human time keeping doesn’t use leap seconds.
2 things it got right:
1. Like the article a great API - Time.current.in_time_zone('America/Los_Angeles') + 3.days - 4.months + 1.hour
2. Rails overloads Ruby's core library Time. You're in 1 object the whole time no swap/wondering.
In the py world, pendulum is close but just like the article, it's cumbersome as it's still a separate obj (i.e. Temporal vs Date) and so you need to "figure out" what you have to manipulate or need to cast it first.
Overloading the core libs is dangerous for a whole host of reasons but for the end developer it's a pleasure to use.
If we could just do `new Date().add({ days: 1})` it would be so easier.
Is this what it looks like? A specific concept like time units being defined as members of more general types like numbers? I.e. if I type `1.` to get auto-complete, am I going to see days, and all the rest, as options?? That API design pattern would be a nightmare!
In more modern languages like Kotlin, there is a notion of extension methods and properties, where you would be able to write a library that allows this syntax, but the .days property would only be accessible in files where you have explicitly imported it (so basically a synthetic sugar for a static function call).
How is that a good thing?
> Rails overloads Ruby's core library Time. You're in 1 object the whole time regardless of what you do.
How is that a good thing?
I would have hoped it'd be ready for wider use by now.
https://caniuse.com/temporal
Not exactly. The language doesn't specify whether the value is copied or not and, precisely because values are immutable, there's no way for a user to tell if it was or wasn't.
For example, strings are also immutable value types, but you can be certain that no JS engine is fully copying the entire string every time you assign one to a variable or pass it to a parameter.
[1] https://momentjs.com/docs/#/-project-status/
[2] https://github.com/moment/luxon/discussions/1742#discussionc...
And a few years later, I'm still using Moment.
And now I'm still using Moment.
And now...
It's simple. In it's simplicity it left many features on the floor. I just can't connect with the idea that someone would need to constantly be on MDN in order to work with it. It's not so horrible that it defies logic.
That seems to be functionality you'd want to have? Or is the intention you convert your numbers to string first and then back to a Temporal.Instant?
And indeed, the static method Instant.from does accept an RFC 9557 string, which requires a 2-digit hour and a time zone offset, but can omit minutes and seconds:
Temporal.Instant.from("2026-01-12T00+08:00")
If you want Date to act like Temporal then only use Date.now() as your starting point. It generates the number of milliseconds since 1 Jan 1970. That means the starting output is a number type in integer form. It does not represent a static value, but rather the distance between now and some universal point in the past, a relationship. Yes, Temporal is a more friendly API, but the primary design goal is to represent time as a relational factor.
Then you can format the Date.now() number it into whatever other format you want.
https://javaalmanac.io/jdk/1.2/api/java/util/Date.html
(I can't find the 1.1 docs, but they were the same)
It's one of my favourite examples of how languages pretty much always get date and time hopelessly wrong initially. Java now has one of the best temporal APIs.
It was hopelessly wrong initially, and got even worse when they added the horrible sql Date/Timestamp/etc classes.
With java.time though, it is the gold standard as far as I've seen.
It's just about perfect in every way. It makes it easy to do the right thing and it's very pleasant to read.
https://caniuse.com/temporal
The current global availability of native Temporal is 1.81%. For context, IE11(!) has a higher global usage than Temporal has native support. For my organization, this likely means we're years from being able to use Temporal in production, because getting the polyfills approved is such a hassle.
Keep in mind that even as of December last year, Chrome didn't ship with it yet (i.e. support is less than one month old). Safari still does not.
Checking against version numbers helps cement existing browser monopolies, makes it difficult for new browsers to view websites (even if the browser correctly implements every feature), and encourages everyone to spoof version numbers / browser names which leads to them becoming a less and less useful signal. See any browser’s User-Agent string for an example of this
I mean, the author's conclusion is correct. But I disagree with the rationale. It's like hating an evil dictatorship because they use the wrong font in their propaganda.
Cheers, great read.
fun demos: https://leeoniya.github.io/uPlot/demos/timezones-dst.html
Implementing such a feature has not only no value, it has negative value. When you program libraries or interfaces you ahould think aboit how people will use it 95% of the time and mane that usecase as simple, predictable and free of potential footguns as possible. This is the opposite of that. It feels like something 15 year old me would have programmed after reading the first book on PHP and not something anybosy with any experience could have thought to be a good thing.
This is not to detract from the quality of the article which is a top-notch introduction to this new API.
[0] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Remember: Date and Temporal objects are logically different things. A Date represents an absolute point in time (a timestamp), while a Temporal object represents a human time (calendar date, clock time, time zone). The fact that Dates are used to represent human time for lack of a better structure is the entire problem statement - the hole that all these other APIs like Temporal try to fill in.
I don't really have a problem with the substance of this blog post. I have a problem with this exaggerated writing style. It means deviating from the fundamental purpose of writing itself!
I had to scroll all the way to the end to find the actual point, and it was underwhelming.
> Unlike Date, the methods we use to interact with a Temporal object result in new Temporal objects, rather than requiring us to use them in the context of a new instance
Bro, just be honest. This entire blog post was totally about developer ergonomics and that's okay. We all hate the way Date works in javascript.
Unless you want your website to run in browsers older than a year
Maybe in 10 years we can start using the shiny new thing?