28 ms·
Dates and Times in JavaScript – A New API for Dates from TC39
- flipchart 6y agoDoes this mean I can get rid of moment.js now?
- SwiftyBug 6y agomoment.js is so annoying because if I don't do momentObject.clone() everywhere I end up having many unwanted side-effects.
- flipchart 6y agoI've been burned by this so many times! Code that uses moment is written, tested, and then never touched to make sure you stay sane
- ryzokuken 6y agoThe Temporal API is immutable, so you won't have to deal with it anymore.
- Roboprog 6y agoI have been lucky, then. I pulled in moment about 5 years ago into our group’s stack, but we mostly use it for parsing and formatting date (only) strings for date arithmetic. The government vital records forms we are working with seldom deal with time of day, and when they do, it’s an optional string down to minutes resolution only. I guess all the converting to and from strings coincidentally protected me from mutability. Good to know.
- wyattjoh 6y agoI've switched most of my work that used to use moment over to Luxon[0] now. It's still written by the same authors, but fixes a lot of the drawbacks[1]. [0]: https://moment.github.io/luxon/index.html https://moment.github.io/luxon/index.html [1]: https://moment.github.io/luxon/docs/manual/moment.html https://moment.github.io/luxon/docs/manual/moment.html
- flipchart 6y agoI'm using React Widgets[0] and I prefer moment over Globalize (been through so much pain with this). Maybe it's time to either write a localizer for Luxor or find a new date time picker [0]: https://jquense.github.io/react-widgets/localization/ https://jquense.github.io/react-widgets/localization/
- WorldMaker 6y agoDepending on your specific needs [0], a lot of date localization can be done (painfully, but possibly) directly with Browser Intl [1] calls instead of a library. [0] Current user's current locale is easy. If for some reason you need to show some other locale than what the browser is using you'll likely still need Moment or Globalize. [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- WorldMaker 6y agoLuxon is great. Also, if you find you only really need one or maybe two date time utilities, date-fns [1] is an alternative that that takes an even more modular approach for tinier imports. [1] https://date-fns.org/ https://date-fns.org/
- mattwad 6y agoI've been using date-fns on the backend. It's great; so long as you don't have to deal with timezones, because the functions only accept and return Date objects, which don't support internal timezone. The other day I needed to get the hour of day based on a user's timezone, though. And had to resort to moment-timezone because NO i dont want to have to handle the math on my own.
- kcorbitt 6y agoCheck out https://www.npmjs.com/package/date-fns-tz https://www.npmjs.com/package/date-fns-tz. The API is much less intuitive than the `date-fns` one because javascript Date objects don't store their timezone, but I've used it in a real project and it's workable once you grok the mental model.
- sratner 6y agoPersonally, I prefer Luxon's timezone handling. I get the appeal of not providing custom classes, but _actually changing the underlying timestamp_ to adjust for timezone has always caused nothing but trouble for me. It becomes an all-or-nothing system (you must use `date-fns-tz` to manipulate the dates) with nothing to actually enforce that.
- jacobr 6y agoYou can already use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... for quite a few of moment’s use cases.
- ryzokuken 6y agoNot yet, but fingers crossed, it would reach Stage 3 in a few months.
- pininja 6y agoVery excited about the timezone improvements here! Their cookbook has great examples https://tc39.es/proposal-temporal/docs/cookbook.html#preserving-local-time https://tc39.es/proposal-temporal/docs/cookbook.html#preserv...
- lxe 6y agoYou will still need libraries to do nicely formatted time strings like "next week" or "3 hours ago"
- runarberg 6y agoLook at `Intl.RelativeTimeFormat`[1] and `Intl.DateTimeFormat`[2]. Regrettably Safari is—yet again—lacking with support, but in the meantime there is a polyfill. 1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... 2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- chrismorgan 6y agoI find RelativeTimeFormat to be not as useful as it seems—it’s surprisingly limited in scope and utility. You still have to calculate the magnitude and unit of the distance (“3 hours ago” → (3, 'hour') rather than saying “here’s a Date object that happens to be about three hours in the future, you tell me what unit to show”), and it only supports one unit at a time (“1 day ago” or “27 hours ago”, not anything like “1 day, 3 hours ago”), and it can’t produce anything like “next Tuesday” or “this Friday”. Twice I’ve started with it, twice I’ve tossed it out because in the end it didn’t help my code at all. (Both times I only cared about English, so its replacement which did a better job of formatting values for my situation took pretty much no extra code—for exact equivalence, formatter.format(-n, 'day') for known positive n becomes a simple ternary, `n == 1 ? '1 day ago' : '${n} days ago'` (or if the formatter has the {numeric: 'auto'} option, change '1 day ago' to 'yesterday'); but even with full localisation, I’d still be unlikely to use RelativeTimeFormat.)
- runarberg 6y agoI guess Temporal will help you there[1]: const now = Temporal.now.absolute(); const then = Temporal.Absolute.from( '1989-11-09T22:45:00+0100[Europe/Berlin]', ); const sinceThen = now.difference(then); sinceThen.toLocaleString('en'); 1: https://tc39.es/proposal-temporal/docs/duration.html#toLocaleString https://tc39.es/proposal-temporal/docs/duration.html#toLocal...
- jasonkillian 6y agoI think this is a great proposal and a huge step in the right direction for JS. I am curious though, is there a reason not to just essentially duplicate the Joda[0]/Java[1]/ThreeTen[2] API? As far as I understand, they are generally considered a gold standard as far as datetime APIs. Is it too Java-y that it wouldn't make sense to port to JS? Are there copyright implications? The JS Temporal proposal _does_ as far as I can tell, share many of the underlying fundamental concepts, which is great, but then confusingly has some types, such as `LocalDateTime`, which mean the exact opposite of what they do in the well-known Java API [3]. There is still discussion going on about these details, but from my perspective it seems like the best thing would be to just copy the Java naming conventions exactly. [0]: https://www.joda.org/joda-time/ https://www.joda.org/joda-time/ [1]: https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html https://docs.oracle.com/javase/8/docs/api/java/time/package-... [2]: https://www.threeten.org/ https://www.threeten.org/ [3]: https://github.com/tc39/proposal-temporal/issues/707 https://github.com/tc39/proposal-temporal/issues/707
- Ndymium 6y ago> The JS Temporal proposal _does_ as far as I can tell, share many of the underlying fundamental concepts, which is great, but then confusingly has some types, such as `LocalDateTime` I can't find a mention of LocalDateTime in the Temporal docs, did you mean something else?
- leothekim 6y agoI think he's referring to https://github.com/tc39/proposal-temporal/issues/707 https://github.com/tc39/proposal-temporal/issues/707.
- jasonkillian 6y agoIt's a current WIP idea for the spec: https://github.com/tc39/proposal-temporal/pull/700 https://github.com/tc39/proposal-temporal/pull/700 Figuring out a name is still part of the ongoing discussion, so this specific case of `LocalDateTime` isn't a huge deal, and I might have misrepresented things slightly in my original comment, sorry! But I do think the overall point still stands - that it might be best to just use the same names and terminology as Java does.
- oefrha 6y agoTL;DR: Actual spec: https://tc39.es/proposal-temporal/ https://tc39.es/proposal-temporal/ Less formal docs: https://tc39.es/proposal-temporal/docs/ https://tc39.es/proposal-temporal/docs/ Examples: https://tc39.es/proposal-temporal/docs/cookbook.html https://tc39.es/proposal-temporal/docs/cookbook.html You can try Temporal in the JS console on a doc page.
- leothekim 6y agoSo glad to read that the core objects are immutable. This is probably my biggest gripe of other date/time manipulation libraries, eg moment.js.
- kcorbitt 6y agohttps://date-fns.org/ https://date-fns.org/ is the most popular alternative to moment-js, has an intuitive functional API and treats dates as immutable. I migrate every project I touch over to it since it has so many fewer footguns.
- eropple 6y agoHuh - thanks for the link. The Moment folks also have Luxon, which I've been using, but there's quite a lot more momentum behind date-fns.
- Drdrdrq 6y agoOr give day.js a try. It is basically moment.js without its problems, and pretty popular too. I tried date-fns but found it cumbersome to use... Ymmv.
- erichurkman 6y ago+1 for date-fns. It's not uncommon to look at a downloads in a JavaScript bundle to find out Moment — and its timezone and localization files — are a huge percentage of a download for a single `moment.format()` call.
- pyrhho 6y agoI wanted to use date-fns on the current project. But, the gotcha is due to its lack of timezone support many of its functions are inherently broken (e.g. startOfWeek). So, if you need rich calculations with timezone support watch out!
- tzs 6y agoI'd like to see the JavaScript people, the Java people, the PHP people, the Perl people, the Python people, the C people, the C++ people, and the people for every other significant language that supports functions (either directly or as methods on objects) to get together and once and for all agree on how the heck we are supposed to deal with times and dates. Then all of them should implement that in their standard library, so that going forward we've got one sane conceptual time handling system everywhere. I tire of dealing with the quirks of everyone having their own approach.
- G4BB3R 6y agoCommunity driven libraries APIs are a mess, look at React Native or Js in general. I'd rather a (group of) specialist to develop the API.
- tzs 6y agoSorry for not being clearer. By "JavaScript people", "Java People", etc., I didn't mean the communities. I meant the people who make the standards for those languages.
- mattwad 6y agoIt's not just that. Timezones are the real bugger. Microsoft has their own list of names separate from the standard IANA timezones, for example. If it weren't for timezones, IMO dates are pretty damn trivial. It's just a matter of storing and transferring them properly (in UTC, always!)
- frenchyatwork 6y agoTimestamps are damn trivial. When people use dates, that's all they want 90% of the time. The remaining 10% is where all the hard problems are. For example, lets say I have a store that opens from 8:00-17:00 every day, and it's currently 22:00. How long is it till it opens next?
- noja 6y ago
- ABoldGambit 6y agoGreat proposal, but Temporal is a poor name. Why not, in the age of the import keyword, finally just have a standard library, and import Date from std like a proper programming language?
- politelemon 6y agoI agree, I think there should have been some drop-in replacement which would allow old scripts to continue working but also let new work make use of these improvements with `Date`. I feel that this duality will persist for a long time, and it can lead to answers, documentation and codebases becoming a confusing mess. It's hard to predict exactly what this mess will look like, only... er... Time will tell.
- runarberg 6y agoThere is a proposal for that[1] which introduces a `js:` pseudo-protocol for importing a build in module (or a standard library): import Temporal from "js:temporal"; 1: https://github.com/tc39/proposal-built-in-modules https://github.com/tc39/proposal-built-in-modules
- hyperpape 6y agoI agree Temporal is an odd name for the object representing an Instant. But it shouldn't be Date either. A Date does not have a time associated with it. Java really did a good job here: Instant, LocalDate, LocalDateTime, ZonedDateTime. (If they hadn't already had java.util.Date, they probably could've replaced LocalDate/LocalDateTime with Date/DateTime, but that ship sailed).
- cwp 6y agoTemporal is just the namespace. It has classes called DateTime, Date, Time, TimeZone, Duration etc.
- renw0rp 6y agoAnd people used to complain about Java development being slow and behind other languages... Regarding JavaScript temporals - better late than never I guess.
- ryzokuken 6y agoIt's been WIP for a few years now! It's easily one of the largest changes to the stdlib of JavaScript recently, and things like these take forever to standardize.
- miltonlaxer 6y agoJust gimme epoch time and we're good.
- ryzokuken 6y agoTemporal.now.absolute().getEpochNanoseconds()
- theandrewbailey 6y agoIn Planck time.
- moralestapia 6y agoA comment on the side, >JavaScript Date is broken in ways that cannot be fixed without breaking the web. I really dislike the arrogant tone that many "new" people employ when talking about some "old" thing they are trying to "improve". (Quotes are there to indicate sarcasm). Date is not 'broken', it may just not do whatever the author wishes it did; it is not 'broken' in the sense of failing to perform its intended function adequately. I hope people could change their ways and be a bit more decent in general. Aside from that, I welcome the new API as I think it would be an improvement over what we have now.
- Spivak 6y agoI think https://maggiepint.com/2017/04/09/fixing-javascript-date-getting-started/ https://maggiepint.com/2017/04/09/fixing-javascript-date-get... and https://maggiepint.com/2017/04/11/fixing-javascript-date-web-compatibility-and-reality/ https://maggiepint.com/2017/04/11/fixing-javascript-date-web... are better links for the motivations of what parts of Date can't be fixed without needing a new API.
- ryzokuken 6y agoDate is "broken" in that it aged pretty poorly, has a very non-ideal API surface and exposes developers to a number of footguns, that could, ideally, be avoided. The fact that a vanishingly small percentage of JavaScript developers use Date for non-trivial applications is a great indicator of these failures.
- swrobel 6y agohttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getYear https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- himinlomax 6y agoWill it allow for using TAI?
- ryzokuken 6y agoNot the core API, but a simple custom timezone can be used to implement TAI. I worked on a POC for it, but you can totally test this with the polyfill right now. https://github.com/ryzokuken/temporal-tai https://github.com/ryzokuken/temporal-tai
- deathanatos 6y agoKind of, but not really? The proposal's Absolute represents time in the POSIX timescale, so it is inherently incapable of representing all of TAI, the same as it is inherently incapable of representing UTC. I attempted to test your library's behavior in this regard, but I do not think you are correctly implementing the proposal's TimeZone. TimeZone.getDateTimeFor() is supposed to take an Absolute and return, in your case, the time that absolute represents in TAI (that time, in the TimeZone). But this: var one_before = new Temporal.Absolute(915148799n * 1000000000n); console.log(one_before.toString()); console.log((new Temporal.TimeZone('UTC')).getDateTimeFor(one_before).toString()); console.log((new TAI()).getDateTimeFor(one_before).toString()); emits, 1998-12-31T23:59:59Z 1998-12-31T23:59:59 1970-01-01T00:15:15.148768 That last timestamp being the output supposedly in TAI; but that POSIX timestamp, 915148799 represents 1999-01-01T00:00:30 in TAI. That is, the second line, 1998-12-31T23:59:59 in UTC == 1999-01-01T00:00:30 TAI. The other direction (getPossibleAbsolutes) is similarly effected.
- sunseb 6y agoWhy not using a namespace like stdlib/datetime instead of this weird named Temporal thing?
- ryzokuken 6y agobecause Temporal is not currently used anywhere (as far as we noticed) and it won't break anything while still being descriptive.
- petepete 6y agoSo long as months are indexed by 1 I'm all for it.
- ryzokuken 6y agoThey are!
- tlhunter 6y agoI'm excited to see this land in Node.js! Currently there are only hacky solutions for calculating nanosecond-accuracy wall clock time.
- jeffmcmahan 6y agoThis is one of those glaring problems that somehow was passed over the last 10 times people got together to decide to improve JS. Remarkable that it has taken so long.
- chaostheory 6y agoIt's probably due to Javascript having such a giant ecosystem. I feel that moment and date-fns dull the pain so much that most people just don't care. Otherwise, this would have been solved faster.
- ryzokuken 6y agoIt's been WIP for years now. Just takes a lot of time to standardize something like this, you know...
- SigmundA 6y agoSo can I round trip it to JSON yet, no, bummer...
- chrismorgan 6y agoJSON has a deliberately limited vocabulary, and is never going to be extended. Objects, arrays, strings, numbers, booleans and null, that’s all you’re ever going to get.
- benatkin 6y agoI think it's quite nice! It tries to be as unopinionated as possible, and does a good job at it.
- LittleDan 6y agoIt would be great to hear feedback from everyone on the Temporal survey: https://forms.gle/iL9iZg7Y9LvH41Nv8 https://forms.gle/iL9iZg7Y9LvH41Nv8
- noiv 6y agoAsking for uni-time ignores physics. It just doesn't exist. It can already be measured clocks separated by a meter in altitude run differently. We might have something that works for daily human stuff, but if you leave the planet or ask for Pico seconds, no standard can help...
- jchook 6y agoReminds me of the incredible Time on Unix[1] article. 1. https://venam.nixers.net/blog/unix/2020/05/02/time-on-unix.html https://venam.nixers.net/blog/unix/2020/05/02/time-on-unix.h...
- typescriptfan1 6y agoDate is actually pretty good. * If you're reading UTC dates from the backend and displaying them in local time, new Date(year + 1900, month, day, hour, minute, second) works great. * It's also easy to calculate repeating intervals in local time by using that constructor with getYear(), getMonth(), etc. * Send it back to the server with .toISOString(). Add a .replace('Z', '') on that so .NET binds a DateTime with the right Kind.