10 ms·
JavaScript dates are about to be fixed
- mjcurl 2y agoSurprising it took this long. I think timezones were missing in earlier versions of Python as well. I wonder why they weren't considered.
- pacifika 2y agoAnd PHP
- 8n4vidtmkvmk 2y agoThey were added to php in 2005. Js is at least 19 years late to the party
- 0cf8612b2e1e 2y agoProbably just one of those hard problems which looks easy from the outside. Nobody wants to handle that thankless mess, which is guaranteed to be broken on any of a hundred edge cases.
- kstrauser 2y agoI understood it to be because the TZ library changes frequently enough that it should be an external package. Date math shouldn’t change based on the language version you’re using, nor should you have to upgrade the language when Arizona finds a new way to creatively alter time.
- mjcurl 2y agoHow do other languages handle this? Do they take the timezones database from the OS, which keeps it updated?
- kstrauser 2y agoI think that'd be the worst place to take it from for the same reason. If I build a package using today's current TZ database and it works on my machine, it shouldn't stop working if I share it with someone using an old CentOS from several years ago.
- mjcurl 2y agoYou're right. But then tz updates would need a patch.
- kstrauser 2y agoTrue, but it’s generally a lot easier to patch software than expect someone to update their whole OS. (Generally. I know plenty of shops deployed Exchange in 2009 and it still works so why fix it, goshdarnit! Those people aren’t generally updating their OS either though.)
- a57721 2y agoIn Java, there is a bundled 'tz' file. It gets updated frequently, here's an example: https://bugs.openjdk.org/browse/JDK-8325150 https://bugs.openjdk.org/browse/JDK-8325150 It is possible to update it manually.
- akira2501 2y ago> TZ library changes frequently enough The zone database adds more historic entries than they do modern ones. You can; however, calculate the correct 1942 "summer war time" in the british isles if you're so inclined. The tendency to do this while also copying copyrighted text into the file shows that the zone maintainers are not interested in the same problems most users are. The TZ database is a complete mess. The whole thing should be replaced with a '.timezone' TLD, each civil time keeping authority should get control over it, and TXT records used to publish current TZ information. OS Vendors can cache all that in the OS if they like, but this secondary central time authority has outlived it's usefulness.
- gitroom 2y agoWhat about external libraries like dayjs?
- Xenoamorphous 2y agoI guess the point is that you won’t/shouldn’t need an externak lib for basic date stuff.
- solardev 2y agoIs there a timeline? I've been waiting for Temporal since like 2016 or so and it's still not ready.
- eyelidlessness 2y agoIt’s stage 3, and they offer production-ready polyfills. For a project I work on, that’s a reasonable enough approximation of “ready”. Your project needs may vary. But it should be stable enough to use now with a userland implementation if the API is what you’re after.
- culi 2y agoSafari even has a flag already. I'd expect it to officially land in 2025 though. It's not a focus of Interop 2024 https://wpt.fyi/interop-2024 https://wpt.fyi/interop-2024
- uallo 2y agoWhere can I find production-ready polyfills? https://github.com/tc39/proposal-temporal/#polyfills https://github.com/tc39/proposal-temporal/#polyfills only lists alpha and beta versions.
- et1337 2y agoI think this might be one of those “difficulty curve” memes. On the left, the Padawan: “just use UTC timestamps”. In the center, the journeyman: “no!!! we have to store time zones and translate between them! Time zone awareness!” On the right, the Jedi master: “just use UTC timestamps”.
- echelon 2y agoThis is the language of your engineering team, but not the language of your customer.
- gvkhna 2y agoYes that works for most use cases but there are use cases where you may need to store or shuttle the time zone. For instance you want to know this UTC timestamp was originally created in PDT. You would have to store two variables. Most other languages have this functionality it can be useful and is good to have, probably only needed by Jedi’s too.
- closewith 2y agoYou can make the same meme about this use case, too. One you get to the right, you realise you want two variables for this.
- nafey 2y agoI have always wondered why breaking the timestamp (in UTC) and the timezone into two separate data points and storing both is not the accepted solution. It appears like the cleanest solution to me.
- tisdadd 2y agoFrom my experience, it certainly is. Easy to tell time in sequence as well as local time then. When daylight savings hits you can still calculate well, and can quickly get real time for hours worked out drive time for freight across time zones to follow the hours of service rules.
- 2y ago
- caust1c 2y agoThank god! Presumably this new API will fix the fact that JS does in fact know about some time zones, but not most. Shield your eyes from this monstrosity that will successfully parse some dates using `new Date(<string>)` in some select special time zones, but assume UTC in the other cases: https://github.com/v8/v8/blob/781c20568240a1e59edcf0cb5d713afab63041db/src/date/dateparser.cc#L135-L147 https://github.com/v8/v8/blob/781c20568240a1e59edcf0cb5d713a... This bit me hard in a previous role. :'(
- marcosdumay 2y agoThat's the Chrome V8 standard library? The one "official" thing that everybody uses? It knows about 8 time zones in 4 different offsets, and that's it? I ask because yes, everything on the site points that way. But it's still so hard to believe that some confirmation would be good.
- beeboobaa3 2y agoIt's more about the javascript spec. If the spec says "thou shalt support this and that" and one of the browsers implements more than that, we are now back in the 2000s where one browser may be supported by some websites but others aren't.
- tmpz22 2y agoCanvas by Instructure, one of the largest LMS (learning management system) in the world officially supports all major browsers. Unofficially schools tell students to use Chrome because some tasks fail often outside of Chrome. In particular Safari's default settings for cookies/privacy often causes the system to fail - particularly with integrations that use iframes/popups and other antiquated tricks. The year is 2024.
- deleted 2y ago[deleted]
- lxgr 2y ago
- spaceheater 2y agoWas this blog post written by sonnet?
- tonetheman 2y ago[dead]
- deepsun 2y agoLooks very similar to Java Joda time, released in 2005 (later adopted as java.time package).
- poikroequ 2y agoI get the same impression. Not identical but the whole temporal API seems heavily influenced by Java. Having worked with dates and times in both Java and JavaScript, I'm very happy with what I see in the temporal API. Huge improvement.
- derriz 2y agoEvery language should just copy Joda time's API. It nailed it.
- yas_hmaheshwari 2y agoI also came down to say the same thing -- Joda's library was the best library to deal with date & time ( Now with all the changes copied to the standard library, I haven't used that library in years )
- JasonSage 2y agoAgree! And I like no longer having to use js-joda to support these types :)
- Macha 2y agoIMO, the pattern that Joda popularised is the most robust option for managing dates we've seen so far. If I'm evaluating date/time libraries in a language I'm not used to, ones that looks like their authors have looked at and understood the API of Joda or derivatives are going to be strong leaders.
- deleted 2y ago[deleted]
- paxys 2y agoHaving a good datetime standard is half the battle. The other (more difficult) half is getting broad adoption for it. If it was just a matter of computing within the bounds of my application then there are a bunch of great libraries that make this stuff easy already. However now the question is - if I pass an encoded ZonedDateTime object from my browser/server to a third party, will it be able to interpret it? Realistically I'm just going to convert it down to an ISO string or unix TS as always just to be safe, thus going back to the exact same problem.
- jitl 2y agoTemporal is getting standardized by the IETF so you can expect it will eventually have broad ecosystem support beyond Javascript, here is the RFC https://www.rfc-editor.org/rfc/rfc9557.html https://www.rfc-editor.org/rfc/rfc9557.html
- culi 2y agoSafari even already has a `useTemporal` flag in their technology preview for the upcoming version. But yes I agree. There's no way any other standard could resist a standard adopted by the IETF and implemented by the language of the web
- lxgr 2y ago> RFC 9557 Date and Time on the Internet: > Timestamps with Additional Information Oh, cool, we're finally adopting TAI!
- burntsushi 2y agoIf you drop the time zone, then you lose essential context that the consumer won't have unless you encode the time zone out of band. And no, an offset is not a time zone. The answer to this is RFC 9557, which was recently published. Rust's Jiff library (of which I am the author) supports it. And I believe java.time supports it. Otherwise, yes, adoption will take time. But it's the right way forward I think.
- wging 2y ago> In other words, the function responsible for transforming a timestamp into a human-readable date is not injective, as each element of the set of timestamps corresponds to more than one element of the "human dates" set. The author confuses the concept of injectivity and well-definedness. For an injective function f, it has to be true that given distinct a and b, f(a) != f(b). That's not the problem here; rather the problem is that for a timestamp t there's no unique human-readable date x such that f(t) = x. That's well-definedness, not injectivity. https://en.wikipedia.org/wiki/Well-defined_expression https://en.wikipedia.org/wiki/Well-defined_expression You could talk about the inverse function, from human-readable dates to timestamps, and correctly point out that that function is not injective, because more than one human-readable date maps to the same timestamp...
- jdthedisciple 2y agoBut how does either problem apply to timestamps? if t is 17943000... whatever which translates to say 03:50 AM on Mar 16, 2020 in Greenwich (i.e. UTC+00.00) then it can be converted to any other human readable zoned time. Where is the issue?
- wging 2y agoThe ability to convert it to any human-readable time is actually the problem: without additional information you don't know which one to pick, and are forced to make certain assumptions, such as using the user's local time zone or defaulting to UTC. That's the point of the section of the article I quoted above. For example, given just a timestamp, you don't even know what day it was. Was the user in New York? That 3:50am was actually 11:50pm on March 15th.
- jdthedisciple 2y agoI genuinely still don't get it, but why do you need to fix the reference point once and for all? I would assume in 99% of cases the user is simply just interested in his local time anyway. If you really need the location info, then you would obv have to make some other tradeoffs like either 1) always store the location alongside the timestamp or 2) complicate (probably massively so) the time format, storing and parsing/processing logic But I don't see how that's an issue of UTC timestamps per se rather than being an issue of requiring more information than just time (i.e. time AND location at the time). Again, really would appreciate an explanation of where I am mistaken here because thus far the whole point of OP seems like a trivial non-issue to me.
- Waterluvian 2y agoIs there any built in for human strings for durations and times? “5 days ago.” “3 hours and 33 minutes.” I’ve found this kind of thing to be the main reason I have to drag MomentJS along for the ride.
- ramesh31 2y ago>I’ve found this kind of thing to be the main reason I have to drag MomentJS along for the ride. Likewise. It feels long overdue to have template based formatting natively.
- simonw 2y agoI’ve written versions of that half a dozen times over my career. I recommend ditching MomentJS and pasting in your own ~15 line implementation. I’m confident ChatGPT or Claude will write you one with one-shot prompt that does exactly what you want. Here’s an attempt at that: https://chatgpt.com/share/9bfe1d60-34cc-46fc-8327-3474c4a7d6ba https://chatgpt.com/share/9bfe1d60-34cc-46fc-8327-3474c4a7d6...
- jayflux 2y agoYes! You’re looking for DurationFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... which will work with Temporal types
- Waterluvian 2y agoThis looks perfect! Just gotta wait until anything supports it. I’m hoping it’s progressing and there’s plans to adopt it.
- roblh 2y agoI sure hope so. Moment + Moment TZ = just shy of200kb gzipped. Learned that one the hard way the other day.
- jitl 2y agoIt’s already available in browsers as part of Intl, no need to wait for Temporal https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- 38 2y agoabout time, Go has had this since 2012: https://pkg.go.dev/time#Date https://pkg.go.dev/time#Date
- foepys 2y agoGo probably has the last standard library I would take as a reference for my own datetime implementation. Their datetime formatting implementation is simply nuts. Why not follow standards? Why the NIH?
- 38 2y agoagreed the format parser is stupid, but thats more a cosmetic issue. its had the ability to create location aware dates since the first version 12 years ago
- godisdad 2y agoIt's about.... time
- pryelluw 2y agoI was going to post: Well, about time.
- radicalbyte 2y agoCan we fix the numeric types next? Having the integer types and decimal types would resolve a whole lot of issues.
- jitl 2y agoI can’t remember wishing I had int32 or uint8 if that’s what you mean. Not having int64 or int128 is kind of annoying but bigint fills in there fine.
- SushiHippie 2y agoI think they mean splitting the "Number" [0] type into an integer type and a decimal type. Currently the "Number" type is used for every number and it gets stored as a double, and can "only" represent "integers" safely in the range of ±(2^53 -1). Though there is a "BigInt" [1] type. [0] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data... [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#bigint_type https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data...
- radicalbyte 2y agoMainly: * Integer types of various sizes (for efficiency) and so you don't have to constantly do floating point comparisons (i.e. equal within a small delta) and generally have better compatibility with other languages. * Decimal floating point type so you can work in base-10 and don't have rounding issues. Plus all of the error checking you get for free if you're using typescript instead of raw-dogging it with plain javascript or coffee-script :-)
- scottlamb 2y agoTemporal will be really nice in that it supports remote time zones, allows you to iterate through daylight saving transitions, etc. I can't wait for it to be fully taken advantage of by things such as mui's date time picker. Imagine if after selecting the fall back day, it saw the transition and let you pick a time during the extra hour. If after selecting the spring forward day, it wouldn't let you pick a time during the hour that doesn't exist. Today that doesn't work because everyone uses different crappy third-party libraries and mui functions on top of a lowest-common adapter that certainly doesn't do stuff like "show me the DST transitions in this day". This stuff matters sometimes; a user of my NVR wanted to save a clip during the fall back hour and got the wrong result because these things just don't work right today. https://github.com/scottlamb/moonfire-nvr/issues/244 https://github.com/scottlamb/moonfire-nvr/issues/244
- Javiliano 2y agoFrom the article: "Let's consider an example: suppose I want to record the moment I make a payment with my card. Many people might be tempted to do something like this: const paymentDate = new Date('2024-07-20T10:30:00');". What? I don't think anybody would define a date like this to record some moment. Most developers would simply use new Date() without any parameters, thereby creating a timezone-safe absolute underlying timestamp value. This value then is of course stringified relative to the timezone of the caller when retrieving it, but that's expected. The new Temporal api might be nice but it doesn't need flawed examples to make its case.
- deleted 2y ago[deleted]
- Y_Y 2y agoUnless the payment already happened?
- kibwen 2y ago> The Temporal API represents a revolutionary shift in how time is handled in JavaScript, making it one of the few languages that address this issue comprehensively. Note that there's also a Rust datetime crate, jiff, that's inspired by the Temporal API and features zone-aware datetimes (from burntsushi, author of ripgrep and Rust's regex library): https://crates.io/crates/jiff https://crates.io/crates/jiff
- burntsushi 2y agoYes! A number of projects have already adopted Jiff too. numbat and gitoxide to name two big ones. :-)
- digger495 2y ago"fixed" And won't be available in non-chromium browsers and LTS versions of Node until 2028.
- strbean 2y agohttps://www.npmjs.com/package/temporal-polyfill https://www.npmjs.com/package/temporal-polyfill
- SahAssar 2y agoWhats your source for it not being available in browsers/node until 2028? Update cycles are pretty quick these days for browsers and mozilla/safari has been pretty good to add APIs that don't increase attack/privacy/interface surface.
- drunkencoder 2y agoStill don’t get it. Is it to be able to show the user a local time for the timestamp? If that is a requirement , why not just also store the timezone along with the utc timestamp? Should the date-object really know this?
- jitl 2y agoThe problem is that the result of toUTCTimestamp(datetime: January 1st 2077 1:15am, timezone: New York) may be X today, but timezone rules could change soon, and then it becomes Y tomorrow. If you've only persisted (unixTime: X, timezone: New York) in the database and you try to turn X back into a local time, maybe now you get December 31, 11:45pm. If you're a calendar application or storing future times for human events, people will think your software is broken and buggy when this happens, and they will miss events.
- dudeinjapan 2y agoSince timezone definitions change, how do we guarantee consistent behavior across browsers and browser versions?
- prmph 2y agoGood, I also used to think storing timestamps in UTC was sufficient. The examples really explained the problems with that well. One other issue to note is that, if you store dates in UTC, now the fact that they are in UTC is a tacit assumption, probably not recorded anywhere except in organizational memory. So the new API will be a very welcome addition to the JS standard library. However, and this is probably a bit off-topic, why are the ECMAScript guys not also addressing the fundamental reasons why JS continues to be somewhat a joke of a language? - Where are decimals, to avoid things like `parseInt(0.00000051) === 5`? - Why are inbuilt globals allowed to be modified? The other day a 3rd-party lib I was using modified the global String class, and hence when I attempted to extend it with some new methods, it clashed with that modification, and it took me and hour or two to figure out (in TS, no less). - Why can't we have basic types? Error/null handling are still haphazard things. Shouldn't Result and Maybe types be a good start towards addressing those?
- troupo 2y ago> Why are inbuilt globals allowed to be modified? Because that was the original behavior, and you can't just change that behaviour, or half of the web will break (including that 3rd party lib and every web site depending on it) > Why can't we have basic types? ... Shouldn't Result and Maybe types Neither Result nor Error are basic types. They are complex types with specific semantics that the entire language needs to be aware of.
- mirekrusin 2y agoThey could use new directive though, ie: "use awesomeness";
- troupo 2y agofrom future import awesomness
- prmph 2y agoSo clean the language up, call it a slightly different name if you want, and let those who want to go modern do so. For those who can't, offer maintenance but no major new features for the original version. Being wedded to mistakes made in the past for fear of breaking current usage is the root of all programming language evil.
- deleted 2y ago[deleted]
- jonstewart 2y agoOh good, from the language that brought us WAT, a new complicated approach to timestamps, what could go wrong.
- fzeindl 2y agoscnr So JavaScript gets what Java got in version 8, 10 years ago?
- tux1968 2y agoThe Java team didn't initiate the process of making it an Internet Engineering Task Force standard; whereas this team did. Even though this is JavaScript centered, it really represents a much broader effort, that should help interoperability between languages and across online systems.
- fzeindl 2y agoWhile the IETF might move slower, Java has standards as well. The java-date-time API standardization started in 2007: https://jcp.org/en/jsr/detail?id=310 https://jcp.org/en/jsr/detail?id=310, than a JEP was created in 2012: https://openjdk.org/jeps/150 https://openjdk.org/jeps/150
- tux1968 2y agoThe point was that language specific standards aren't nearly as important as broad industry standards.
- ta8645 2y agoThis is a step in the right direction, but it really needs to be supported everywhere so that there isn't friction when crossing into Javascript, and out to a database or other language. A language-agnostic test suite should be provided, including every edge case, so that this standard can be implemented everywhere.
- jitl 2y agoYes, it's being standardized by the IETF, here's the RFC: https://www.rfc-editor.org/rfc/rfc9557.html https://www.rfc-editor.org/rfc/rfc9557.html
- layer8 2y agoThe use of “instant” to denote a time coordinate always rubbed me the wrong way. While “instant” arguably can mean a precise point in time (“in that very instant”), the primary dictionary definition is a (very small) time interval. This is also reflected in the meaning of “instantly”, which does not mean “simultaneously” or “at the same point in time”, but rather something like “immediately after”. Similarly for the adjective “instant”, which likewise generally implies a chronological succession, however short. I can’t quite put my finger on it, but it instinctively feels off to me to use it to denote timestamps.
- zeroonetwothree 2y agoThe first dictionary definition of instant is “a precise moment in time”. That usage seems perfectly to fit how it’s used for a timestamp.
- layer8 2y agoThat might depend on your dictionary: https://dictionary.cambridge.org/dictionary/english/instant https://dictionary.cambridge.org/dictionary/english/instant In any case, it’s about how the word is normally used. In normal language you never say something like “those two instants are three hours apart”, or “three hours passed between the two instants”. In contrast, you would say something like that with “points in time”. For example. one can say “this was observed at two different points in time”. Nobody would say “this was observed at two different instants”.
- the__alchemist 2y agoThank god. Javascript is the only language where I... wait for it... roll my own datetimes. Moment's central failure, beyond the surprise mutability, is the conflation of Dates and Times with Datetimes. They are not the same, and this causes so many problems. Python's Arrow library made the same mistake, likely inspired by Moment. I've heard JS devs insist that Dates and Times have no place as standalone constructs outside of a Datetime, but this is incompatible with practical use cases. Rust's Chrono? Outstanding. You can find flaws, but it's generally predictable, and most importantly, has fewer flaws than those in other languages. Python's? Kind of messy, but usable. JS's Date and Moment? Unusable.
- lxgr 2y ago> I've heard JS devs insist that Dates and Times have no place as standalone constructs outside of a Datetime As somebody having both caused and fixed many time-related bugs in a financial/payments context, this sentiment is creating an almost physiological reaction at this point. If your real-world process is concerned with things happening on particular days, don't represent these as midnight, i.e. 00:00, of that day. You'll thank me the day your company starts hosting servers or interacting with a customer/vendor in a different timezone. Essentially, this is just a corollary of "don't imply more precision in your internal data representation than was present in your data source", but it bears repeating when it comes to date/time processing too. (And please, please don't ask me about the difference between "Y" and "y" in Java's SimpleDateFormat, but look it up before you ever use it, thinking they're equivalent... Because on some days of some years, they are not.)
- sorokod 2y agoDon't wish to be a java apologist but SimpleDateFormat lives in the java.text package, far from where date/time stuff is.
- lxgr 2y agoHow is a function that converts an internal date/time representation to an external/string-based one not "date/time stuff", regardless of the package it happens to be in?
- ravenstine 2y ago> Even when working with dates on an ISO format, including the offset, the next time we want to display that date, we only know the number of milliseconds that have passed since the UNIX epoch and the offset. But this is still not enough to know the human moment and time zone in which the payment was made. Can someone explain to me what this means? ISO date strings should capture that exact information. Sure, there are caveats to storing dates/times, but I find the idea that JavaScript (or any language) needs built-in constructs for this purpose to be questionable. Beyond that, both Temporal and Date solve what should be very simple problems in very complicated ways. I've yet to run into a circumstance where ISO strings don't suffice.
- mmis1000 2y ago> but I find the idea that JavaScript (or any language) needs built-in constructs for this purpose to be questionable. Either this, or every project starts with a 200kb date library import. In reality, I haven't met a single project that I don't need to deal with dates and timezone. And I almost always have a date.ts in my utils library because I don't want to import a giant date library either. But for real, developers shouldn't need to deal with this. These operations and constructs that every sites need should be build into the language itself.
- ravenstine 2y ago> Either this, or every project starts with a 200kb date library import. It's interesting you say this but then go on to explain that you roll your own date library. Doesn't that discredit the idea that the alternative for every project must be a 200kb date library? I agree that most projects work with dates and time zones in some way, but that doesn't mean we'd have to use moment.js in the absence of the Date API. There's plenty of incompetent developers that would still do as such in the current year, but then this becomes a whole different argument.
- mmis1000 2y agoThe 200kb is already an underestimate. If you search temporal date polyfill and check the js size. It's 200kb for 'single' language. Date is much more complex than you expect. And even yourself don't use it. The library authors will. There will be someday that people take the existence of temporal date api for granted. And you have no choice but import the polyfill if you want to deal with old browsers.
- scosman 2y agoI had to write a bunch of date logic in go a few weeks ago. Assumed it would be riddled with bugs, so wrote a dozen test cases for time zones, daylight savings, and leap seconds. Everything just worked. Not one bug. A good library is so so helpful for complex use cases like dates.
- jrflowers 2y agoSeems shortsighted to make dates fixed. The date changes almost every day
- izwasm 2y agoI don't get it, you can already get the user time zone with javascript ``` Intl.DateTimeFormat().resolvedOptions() ``` a good library like dayjs can handle timezones
- jitl 2y agoIt's quite annoying to deal with different library dependencies that all picked a different userspace library for something that should be standardized. For example, you might ship a date picker component using dayjs, but I already adopted Luxon in my application, so now I need to write some janky adapter or end up using both. I would love to not have to import dayjs or another userspace library, so that i can pass datetime-with-timezone to other libraries and instead use an IETF standard way of handling time that's backed by performant native runtime code. In my experience, userspace timestring parsing and timezone conversion can also be a surprising CPU bottleneck. At Notion, we got a 15% speedup on datetime queries by patching various inefficiencies in the library we selected. The runtime can be more efficient as well as saving page weight on tzdata and locale stuff.
- dclowd9901 2y agoThe value of this didn’t really hit me until this line (which frankly should be the lede): “This precision means that regardless of DST changes or any other local time adjustments, your date will always reflect the correct moment in time.” Probably a failing on my part but I had somehow assumed all this time that calculating DST was a separate concern from time zone offset, given how tremendously opaque it can be. To my knowledge, there is an area in Arizona that does observe DST, within an area that does not observe DST, within an area that does, within Arizona at large, which does not. Does this API really accurately represent this peculiar arrangement? It looks like canonically there’s an America/Shiprock timezone but you’d think you’d need at least 4 to accurately represent the various areas. https://upload.wikimedia.org/wikipedia/commons/3/38/AZNMUT_DST_observance.png https://upload.wikimedia.org/wikipedia/commons/3/38/AZNMUT_D...
- thaumasiotes 2y ago> To my knowledge, there is an area in Arizona that does observe DST, within an area that does not observe DST, within an area that does, within Arizona at large, which does not. Does this API really accurately represent this peculiar arrangement? What are you envisioning? That sounds like two timezones, with different regions belonging to one or the other. Does it matter to the API if two regions that aren't contiguous with each other share a timezone?
- thangalin 2y agoOn a related note, here's an algorithm for parsing user input into a sanitized time format: String.prototype.toTime = function () { var time = this; var post_meridiem = false; var ante_meridiem = false; var hours = 0; var minutes = 0; if( time != null ) { post_meridiem = time.match( /p/i ) !== null; ante_meridiem = time.match( /a/i ) !== null; // Preserve 2400h time by changing leading zeros to 24. time = time.replace( /^00/, '24' ); // Strip the string down to digits and convert to a number. time = parseInt( time.replace( /\D/g, '' ) ); } else { time = 0; } if( time > 0 && time < 24 ) { // 1 through 23 become hours, no minutes. hours = time; } else if( time >= 100 && time <= 2359 ) { // 100 through 2359 become hours and two-digit minutes. hours = ~~(time / 100); minutes = time % 100; } else if( time >= 2400 ) { // After 2400, it's midnight again. minutes = (time % 100); post_meridiem = false; } if( hours == 12 && ante_meridiem === false ) { post_meridiem = true; } if( hours > 12 ) { post_meridiem = true; hours -= 12; } if( minutes > 59 ) { minutes = 59; } var result = (""+hours).padStart( 2, "0" ) + ":" + (""+minutes).padStart( 2, "0" ) + (post_meridiem ? "PM" : "AM"); return result; }; I posted it a while back to the following thread: https://stackoverflow.com/a/49185071/59087 https://stackoverflow.com/a/49185071/59087 One of my minor bug bears is why we humans have to enter time into input fields in such rigid formats when there's a straightforward algorithm to make such inputs far more natural.
- Denvercoder9 2y agoYour function converts "0:23" into "11:00 PM".
- thaumasiotes 2y agoIf you were a human, you would have written "00:23", not "0:23". It'll also convert "0:45" into "00:00AM" (and "0:23" into "11:00PM").
- Denvercoder9 2y ago
- thedougd 2y agoDoes this mean I will no longer have to suffer with so many sites only offering relative times in lists without even hover for absolute date & time? I’m looking for a particular build or deployment near a certain date and time and I must first calculate how many days ago it was then binary search through the items from that day.
- eyelidlessness 2y ago> Does this mean I will no longer have to suffer with so many sites only offering relative times in lists without even hover for absolute date & time? Why would it mean that? It seems tangentially related at best. The sites you’re complaining about don’t use the presentation you’re complaining about for lack of more precise Date APIs, they use it intentionally as a feature (even if you consider it a misfeature).
- wnevets 2y agoDealing with dates in JS is easily one of the most annoying parts of the language. I usually avoid it at all cost.
- culi 2y agoAm I naive? It seems like POXIS ignoring leap seconds is a major mistake. Wouldn't a standard that means "number of seconds since January 1, 1970 UTC" be much more useful than "number of non-leap seconds since January 1, 1970 UTC"? Does this mean that converting two DateTimes into their POSIX time and subtracting them will not yield an accurate representation of number of seconds between two timestamps?
- lxgr 2y ago> Does this mean that converting two DateTimes into their POSIX time and subtracting them will not yield an accurate representation of number of seconds between two timestamps? It will indeed not, and if you care about that difference, you should not do that, and use something like https://github.com/qntm/t-a-i https://github.com/qntm/t-a-i instead. > Am I naive? It seems like POXIS ignoring leap seconds is a major mistake. Depending on your needs it can be either seen as a massive mistake or a big convenience win. In either case it's arguably not a complaint with POSIX, but rather with the commercial and scientific world at large using UTC instead of TAI (and there are indeed people arguing for abolishing leap seconds!). POSIX in turn just followed that standard.
- culi 2y agoIf we simply stored all timestamps as "number of seconds since X" then we could safely convert that to whatever timezone, apply whatever leap adjustments, apply daylight savings time, convert to whatever calendar, etc anywhere we want Instead of browsers/libraries handling all the complexity (standards and localization, dst, leap seconds, etc), couldn't we just do all our math and logic in this format and then convert back to whatever when we need to display a time to a user. It seems like saving a #seconds along with lat/long information is enough to handle all timestamp use-cases.
- lxgr 2y ago> If we simply stored all timestamps as "number of seconds since X" That works – if you never want to represent dates in the future (because we don't know how many leap seconds there will be in the future). But that way, you'd be incapable of implementing even a trivial calendar application involving more than one timezone. > couldn't we just do all our math and logic in this format and then convert back to whatever when we need to display a time to a user We could – using all the libraries encapsulating that complexity. > It seems like saving a #seconds along with lat/long information is enough to handle all timestamp use-cases. That's even worse, since often that's not available, and even if it is, now you need a database representing local UTC offsets as polygons on the surface of the earth!
- llsf 2y agoIs this article arguing that a timestamp should include space ? I get that timestamp can be display differently depending on the space (i.e. TZ and locale). But does it mean that we need to add the space component to a timestamp ? Feels like 2 distinct things. Sure, when I record an event, I might not only want to record "when" it happened, and "where". But the "where" does not change or impact the "when", and vice-versa. Those feel 2 distinct properties to me, and I might want to store them separately. Maybe I am missing something.
- Macha 2y agoFor past timestamps, arguably a UTC record of when it happened is sufficient as converting it for display in a specific timezone is a fixed, and no longer mutable transformation. For a future looking time, it's not sufficient, because e.g. DST rules might change, timezones might change (and there's usually at least several occurrences a year of some timezone or DST rule changing somewhere in the world). If you have a reservation for the concert hall from 6pm next September, you don't want to show up there with the previous show still occupying the venue just because your government abolished DST in the year in between.
- llsf 2y agoPerfect explanation. I did not thought about future events and changing TZ rules (which happen obviously depending on the country/government). Thanks!
- lxgr 2y agoKind of, but space in the social sense of "set of places and people agreeing on what is local time", not the physical one. We need to record that whenever we want to talk to people about time and schedule things for them, just like we need to record their language and regional format preferences. In other words, you might not need that level of metadata for a physical simulation, but you'll definitely need it for a calendar app. For everything in between, it depends, and the safest bet is accordingly to just do it, if you can.
- crote 2y ago
- penguin_booze 2y agoFor once, an article on the internet has commas in the right places. Well done.
- moomin 2y agoIt is a source of wonder to me that every programming language I know has to go through this process where the design half-asses time handling and end up coming back decades later with a whole new API which, inevitably, fewer people use than the older, footgun-friendly API.
- preya2k 2y agoCan anyone shed light on the timeline behind the rollout of the Temporal API? I've been reading about it for many years, and it's always "soon" or "right around the corner". I'm kind of annoyed by all this teasing.
- AlexErrant 2y ago"about to be fixed" is pretty clickbaity with no substance. From the July TC39 meeting [0]: > After 7 years, Temporal is close to done. Our only focus is making sure in-progress implementations are successful, by fixing corner-case bugs found by implementors, and making editorial changes to improve clarity and simplicity. It's not (yet) on the October TC39 agenda [1]. The Chromium implementation issue hasn't been updated since 2022. [2] Webkit's implementation issue was updated once this year... to add a blocker [3] V8 is passing 75% of test262's tests, and JavascriptCore is passing 41%. Spidermonkey is a no-show. [4] Note that test262 is incomplete and hasn't seen activity this year [5], so those percentages may decrease over time. "about to be fixed" ehhhh. If it lands this year I'd be surprised. [0] https://ptomato.name/talks/tc39-2024-07/#2 [1] https://github.com/tc39/agendas/blob/main/2024/10.md [2] https://chromestatus.com/feature/5668291307634688 [3] https://bugs.webkit.org/show_activity.cgi?id=223166 [4] https://test262.fyi/#|v8,v8_exp,jsc,jsc_exp,sm,sm_exp [5] https://github.com/tc39/test262/issues/3002
- doctornoble 2y agoYeah, I’ve been waiting for this for years and not optimistic it’s “near”. The polyfill is too heavy and the services we deal with seem to cover the whole range of dates and times. Julian, epoch, ISO-8601.
- LegionMammal978 2y agoIt's a shame that this new API still doesn't support querying leap-second information within web-based JS, in any shape or form. The only solutions are either to store a big list yourself and keep it updated, or download it from someone else's website and trust them to keep it updated and keep their CORS settings permissive. Meanwhile, most OSes are fully aware of leap seconds (or at least, browsers could easily include an updated list), but there's just no way to retrieve them from the inside.
- theteapot 2y ago> "... number of milliseconds since the EPOX given this CET instant" What? UNIX epoch? Central European Summer Time?
- masswerk 2y agoI wonder, when dealing with human readable formats, is there a notation dealing with the repeated hour at the end of daylight saving time (DST)? E.g., in the US, DST ends on Nov. 3, 2024 and the hour from 1:00 to 2:00 am will be repeated. Is there a way to distinguish the second pass from the first one?
- jjnoakes 2y agoFor human-readable purposes I usually just stick in the timezone. 1:59am EDT plus 1 minute is 1:00am EST.
- Asmod4n 2y agoWhat do the authors of tzdata say about it?
- deleted 2y ago[deleted]
- trescenzi 2y agoI’ve been using Temporal, via a different polyfill than in the article[1], in production for about 6 months now. It’s a game changer. But JavaScript people are also broken from years of not having this so it’s been a hard sell. To many it’s just extra work. We’re about to start doing international stuff though so really hoping it becomes clear why it’s amazing to the team soon. [1]: https://github.com/js-temporal/temporal-polyfill https://github.com/js-temporal/temporal-polyfill
- robjwells 2y ago“About to be fixed” ≈ “this is the year of Linux on the desktop” Wake me up when a browser ships Temporal. Edit: Here’s Temporal on caniuse.com: https://caniuse.com/?search=temporal https://caniuse.com/?search=temporal Handful of APIs in the Safari Technology Preview, otherwise nada. I look forward to Temporal landing but it is still a very long way off.
- ak_111 2y agoThis thread is making me panic that I don't understand handling time in programming and now I am paranoid that one day it will bite me hard. What is a good primer in understanding most of the serious issues raised in this thread and how they manifest themselves in (preferably) languages like Python?
- codersfocus 2y agoRead the luxon.js docs (the timezone section.) It’s the successor to moment.js. They do a great job explaining the common footguns developers face.
- Kailhus 2y agoInteresting, some of us migrated to date fns since
- codersfocus 2y agoIf you read GitHub issues for datefns you’ll find examples where it doesn’t handle timezones correctly
- namtab00 2y agoThis is for .NET, but the issues described stand for any stack: https://codeblog.jonskeet.uk/2019/03/27/storing-utc-is-not-a-silver-bullet/ https://codeblog.jonskeet.uk/2019/03/27/storing-utc-is-not-a...
- austin-cheney 2y agoThe military solution is to standardize on a zero offset time, specified as time zone Zulu. That is just a named time zone representing the TAI variant of UTC. The challenge is that local computer time comes from a time and time zone set locally and stored in the hardware CMOS. That is not precise, varies from computer to computer, and provides all the offset problems mentioned in the article. Network hardware solved for that long ago using NTP. So the military applied a similar solution as an OS image enhancement that receives updates from a network time service whose time is defined according to the mesh of atomic clocks. Then it does not matter what offset is shown to the user by the OS when all your reports and data artifacts log against a universally synchronized time zone defined by a service. The military solution works fine for the military but it requires centralized governance normal people do not have.
- hamandcheese 2y agoThe article would be more convincing if it used more examples of dates in the future. For timestamps (i.e. recording things that happened), I still believe all you need is UTC and a location. The bank example is just a matter of poor UX, not lost information (surely the bank could map transactions to a local time zone if they wanted).
- mikeocool 2y agoIf they don’t fix the 0 indexed months, this will all be for nothing.
- magarnicle 2y agoYeah, but imagine how much would break if they changed that.
- crooked-v 2y ago"About to" feels like a stretch to me, unless there's actual evidence for that. Temporal has been stuck in the bikeshedding phase for years, the same as a bunch of other promising JS proposals.
- Separo 2y agoHow would I handle this with Postgres?
- stpn 2y agoSort of relatedly, I’ve been fighting Safari bug for years that feels like it has to be related to dates in js. Safari’s saved credit card support works pretty well, but when I switch between US and Asia timezones the expiration date will shift by a month in one direction. My best guess is that they store the expiration as midnight local time on the 1st of the month in a js Date which can shift when you travel outside of that timezone.
- nikisweeting 2y agoThis is great but I really hope someone contributes strftime / TR35 to the v2 proposal, there's still no way to make date format strings in JS, despite being common in every other language, e.g. "%Y-%m-%d_%H-%M-%S_%s", or "%m/%d/%H/%M:%S". - https://github.com/js-temporal/proposal-temporal-v2/issues/5#issuecomment-1986577328 https://github.com/js-temporal/proposal-temporal-v2/issues/5...
- wruza 2y agoMy projects requirements are usually not timezone-aware, and/or I’m slow to see how this helps these. What I’d like to have (in addition, not as a replacement) is timeless dates. I can store/carry a timezone manually, but give me a proper date[-notime] datatype. I mean, I sort of have it with just “yyyy-mm-dd” and calculating with temporary “T00:00:00Z” suffix. But why would this new format solve my “no timety” impedance mismatch? More specifically, please give me all the components separately and then design interfaces which may accept any number of these and make sure it makes best sense. Dates without times, times without dates, dates or times with or without timezones, dates without months and/or days, days without years and/or months, weekdays, simply timezones, and so on. Having new dates like subj is yet another piece in the date logic tetris you have to play. Stop imagining developer stories and make them all 1x1 square.
- WickyNilliams 2y agoThe Temporal API discussed here includes PlainDate btw. See https://tc39.es/proposal-temporal/docs/plaindate.html https://tc39.es/proposal-temporal/docs/plaindate.html
- sholladay 2y agoAm I the only one who feels like Date is actually a decent API, quite easy to use and good enough for almost everything I’ve ever needed? Temporal seems needlessly complex and not something I want to use. Sure, Date could be better. I wish Dates were immutable. I wish UTC was the “default” instead of having to call all the UTC methods. And sure, formatting via toLocaleString() isn’t the most intuitive way to do things. But… it works and it’s pretty straightforward. If I need time only without the date, there’s a method for that. If I want ISO 8601, there’s a method for that and it’s even the default when the Date is sent in JSON. If I want a UNIX timestamp, there’s a method for that and it’s even the default when the Date is used as a number, which also makes Dates easily comparable and sortable. The `Intl` API has a lot of ways to format Dates. IMO Dates are underrated. Though they could benefit from a more ergonomic formatting method, a la `moment, maybe a more flexible parser, and some support for leap seconds.
- Aardwolf 2y agoHow does this API deal with political timezone and DST changes? Will JavaScript versions come with an updated hardcoded database in the spec, or browser updates, or will it require internet connection to get it from some server? What if 2 clients or a client and a server have different versions of this database, could inconsistency issues arise? Will all past changes keep being handled correctly (e g. if a region changed their timezone or DST rules multiple times in the past, does it take this into account for any past date)? How will the date math work on future dates where the DST rules are not yet known (e.g. could a future date change its display or UTC value after an update)?
- magnio 2y agoTemporal specifies using IANA Timezone Database for all time zone aware implementations and recommends them to "include updates to the IANA Time Zone Database as soon as possible." Moreover: > If implementations revise time zone information during the lifetime of an agent, then which identifiers are supported, the primary time zone identifier associated with any identifier, and the UTC offsets and transitions associated with any Zone, must be consistent with results previously observed by that agent. Basically, the timezone data must not change while a browser tab, a Node program, or a service worker is running. AFAIK, this does not prevent possible timezone data mismatch between different versions of browser and server, or even different browsers on the same machine. https://tc39.es/proposal-temporal/#sec-use-of-iana-time-zone-database https://tc39.es/proposal-temporal/#sec-use-of-iana-time-zone...
- ihyay3 2y agoDeno already supports it as many other web api: https://docs.deno.com/api/web/ https://docs.deno.com/api/web/ Who would have thought that a JS / TS backend framework would not only be a convenient but sane choice.
- deleted 2y ago[deleted]
- Wazako 2y agoThis reminds me of crunchyroll, the anime website, which uses local utc us with fixed times for episode releases. This creates confusion in the rest of the world, because for 2 weeks, there's a time difference until daylight saving time changes in the US.
- ek750 2y agoThis is a great and important topic, one that I’ve bumped into against in past code. I think I understand the basics of time/zones/storage. However, on one codebase I worked on in the past, dates were stored in mysql in a datetime field, with the time set to 00:00:00, iirc. I’m hoping someone knowledgeable about this topic could comment on this. I never could discover why it was done that way. It wrong? Is it right? Based on the other threads here, it seems wrong, but maybe there’s a non-obvious reason to do it this way?
- norswap 2y agoMaybe I'm missing something but it seems like much ado about nothing. Just use a timestamp — if you need to know the associated timezone, just store that as well. Done. But most often (when the timezone where the event was captured isn't relevant to the user or the business logic) conversion to local time is a frontend/view concern.
- steeeeeve 2y agoThis is a solution for a problem that does not exist. It's just unnecessary bloat. If you need to store the time zone specifically, do that. Use a library or create an child object with an extra field. There are very few use cases where you need to know specifically what time zone a given DateTimeStamp was originally stored in.