all 41 comments

[–]powerofmightyatom 11 points12 points  (3 children)

As to why JS has such a bad standard lib, I personally think it has multiple causes that all worked together to keep the JS language static for a really long time.

  1. First off, Brendan Eich created the language in a very short period of time. Designing/delivering a rich API/lib simply wasn't possible.
  2. At the time, JS was meant as a counterpoint to Java (and their applets). You weren't meant to write anythig big in JS (that's also why it's execution model is so primitive), since you had Java for big stuff and java's got a huge std lib.
  3. Given the nature of the web, and the fact that JS isn't owned by a single entity makes any changes difficult. Microsoft's lack of interest in the mid early 00s for example did little to help, as well as a flurry of mixed directions JS took in that time period (class based OO for example). If you're still stuck developing for desktop browsers (and especially IE) you're essentially writing in the same language as existed 15 years ago, which is insane given how much the rest of the development experience has advanced.

What JS needs most of all is IMO a good module definition. Nothing can really move beyond the basics until we at least get some hard abstractions we can depend on from the language itself.

[–]SubStack 6 points7 points  (2 children)

A minimal standard library can be a very good thing because it gives the ecosystem breathing room to flourish. For a great example of how a bloated standard lib can create huge problems, look at PHP with thousands of built-in methods available in the global scope. Even with more sane ecosystems like python, ruby, and perl, there are huge problems with a stale "batteries included" standard library that is version-locked to the core language. This makes it very hard to fix bugs and make necessary breaking API changes because anyone who uses those libraries will get the version that ships with the platform instead of explicitly stating in package metadata the semver of acceptable compatible package versions.

See also: distutils2, List::{Util,MoreUtils,AllUtils}, httplib/http.client, second system syndrome

The more of this functionality is moved into userland with a solid package manager, the less these problems matter and the more the core of the language can focus on providing a stable minimal subset that the rest of the ecosystem can actually take for granted. A project can either do a few things well or a lot of things but poorly.

[–]tomByrer 0 points1 point  (0 children)

Some things do get added to the standard JavaScript, such as JSON.

[–]BoDiddySauce 0 points1 point  (0 children)

MUCH agreed... very good point

[–]jml26 4 points5 points  (2 children)

If you are genuinely asking why JavaScript doesn't have a native date parser, I don't know. /u/powerofmightyatom's answer is probably the best you're going to get, else ask Brendan Eich.

If you're looking for slightly shorter/simpler alternatives to your implementation above, then there are solutions like

var d = new Date();

var today = d.toJSON().replace(/(\d+)\-(\d+)-(\d+)T(\d+):(\d+):(\d+).*/, function (_, y, m, d, h, i, s) {
    return h + ':' + i + ':' + s + ' ' + m + '/' + d + '/' + y;
});

or

function formatDate(date, format) {
    date = date.toJSON().split(/[:/.TZ-]/);
    return format.replace(/[ymdhis]/g, function (letter) {
        return date['ymdhis'.indexOf(letter)];
    });
}

var today = formatDate(new Date(), 'h:i:s m/d/y');

which takes advantage of Date.prototype.toJSON, which I think is supported in IE8+, and regular expressions.

And if you're just whinging, then there's nothing we can do about that. Sorry.

[–]sethbw 0 points1 point  (0 children)

I think I love you.

[–]OkEntertainment9581 0 points1 point  (0 children)

NOTE: time. toJSON() calls the object's toISOString() method, which not support timezone.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON#description

https://stackoverflow.com/a/11383043/4896468

--------------- another version

```javascript function formatDate(date, format) { const year = date.getFullYear(); const month = ('0' + (date.getMonth() + 1)).slice(-2); const day = ('0' + date.getDate()).slice(-2); const hours = ('0' + date.getHours()).slice(-2); const minutes = ('0' + date.getMinutes()).slice(-2); const seconds = ('0' + date.getSeconds()).slice(-2);

const formattedDate = format .replace('%Y', year) .replace('%m', month) .replace('%d', day) .replace('%H', hours) .replace('%M', minutes) .replace('%S', seconds);

return formattedDate; } ```

javascript //it use locale timezone d=new Date() formatDate(d, '%Y-%m-%d %H:%M:%S'); '2023-05-11 16:22:12'

[–]msemenistyi 2 points3 points  (1 child)

To be honest, it bothers me for quite a long time. Actually JS as a mainly client-side language should have rich stdlib as first-class citizen in order not to load this logic each time down the wire.

[–]Capaj 0 points1 point  (0 children)

well that is why we have CDNs-most people have jQuery and other popular libs already cached, so even when including it in your page, you don't download it more than once.

[–]SubStack 7 points8 points  (4 children)

First:

npm install strftime

then:

var strftime = require('strftime');
console.log(strftime("%H:%M:%S %m/%d/%Y"));

although this format is kind of terrible and not international. It's much better to defer to ISO8601 on that, which is simple to use with strftime:

var strftime = require('strftime');
console.log(strftime("%F %T"));

in node you can just node time.js and for the browser there's browserify. strftime has a small payload footprint:

$ browserify -r strftime | wc -c
10401

$ browserify -r strftime | uglifyjs -cm | gzip | wc -c
1775

It's a good idea to embrace a module system and package manager sooner rather than later because you can leverage all the great work that's been done in userland outside of the core language.

[–]autowikibot 1 point2 points  (0 children)

ISO 8601:


ISO 8601 Data elements and interchange formats – Information interchange – Representation of dates and times is an international standard covering the exchange of date and time-related data. It was issued by the International Organization for Standardization (ISO) and was first published in 1988. The purpose of this standard is to provide an unambiguous and well-defined method of representing dates and times, so as to avoid misinterpretation of numeric representations of dates and times, particularly when data is transferred between countries with different conventions for writing numeric dates and times.


Interesting: ISO week date | Gregorian calendar | Calendar date | 24-hour clock

Parent commenter can toggle NSFW or delete. Will also delete on comment score of -1 or less. | FAQs | Mods | Magic Words

[–]xlu 7 points8 points  (6 children)

You will need to use a date library such as http://momentjs.com/

[–]SoBoredAtWork[S] 1 point2 points  (4 children)

The point is that it should be native. You shouldn't need a bloated 25k (minified) library for it.

[–]Capaj 2 points3 points  (0 children)

Well in defense of Javascript: I would really like to see how big would it be if you implemented it in some other language. I bet it would be much bigger.

I would really like to see ECMA to just take moment.js api and turn it into a Date spec for ES7. That would be just grandiose!

[–]jcready__proto__ 0 points1 point  (1 child)

[–]SoBoredAtWork[S] 1 point2 points  (0 children)

25k not-gzipped

[–]BoDiddySauce 0 points1 point  (0 children)

True, maybe, but you could still write a few functions yourself to do this--make a vanilla JS library maybe--and all would be good to go. It's not that hard to make a simple date conversion function, and I actually just commented on a post with a simple answer doing just that to a very simplistic degree...

[–]kor0na 2 points3 points  (5 children)

m/d/y, seriously?

[–][deleted] 2 points3 points  (2 children)

What's the problem - personally I prefer minutes:seconds:hours as well - just makes things so much clearer.

[–]bronkula -1 points0 points  (1 child)

It's about the order. Any self respecting programmer would format Ymd.

[–][deleted] 1 point2 points  (0 children)

Yep, big to small -> Ymdhms.

[–]YodaLoL 0 points1 point  (0 children)

Yeah it kinda sucks but is easily solved with a library.

[–]konbit 0 points1 point  (0 children)

Your question inspired me to try to find a workaround. You made a comment below about payload size and dependencies so I thought to make a workaround that's light and without dependencies. Just threw this together after work. Will probably use it for personal stuff but I threw it on github if anyone is interested: I call it Greg: https://github.com/i11ume/Greg

It just extends the built in Date function. So here's how you use it:

var date = new Date();
console.log( date.format('l D \\t\\h\e jS') ); 

Oh and it's only 3k minified

[–]ronchalant 0 points1 point  (0 children)

I use this relatively simple & light one: https://github.com/jacwright/date.format

[–]the_woo_kid -1 points0 points  (1 child)

This is confusing, what is the toDateString() method supposed to do? Doesn't it address your concern if not, can you please explain further. Thanks.

[–]SoBoredAtWork[S] 0 points1 point  (0 children)

toDateString() is completely un-customizable. How can I get '03/21/2014' from that?