r/javascript • • May 29 '13

Javascript Makes Me Cry: Turning a Date into a String

http://ralsina.com.ar/weblog/posts/javascript-makes-me-cry-turning-a-date-into-a-string.html
3 Upvotes

85 comments sorted by

16

u/Rhomboid May 29 '13 edited May 29 '13

With the exception of the naming of methods, everything you are complaining about is inherited directly from C/POSIX. Have a look at the definition of struct tm from <time.h> and see if it's familiar. This interface dates back decades, to at least the early 1980s BSD Unix 2.x.

-1

u/ralsina May 29 '13

Perhaps you missed the complaint about not having a sprintf and strftime equivalents, so not quite everything ;-)

The only thing I see there that I complain about in the post is the zero-based months and the way the year is stored.

However, how things are stored is not the point at all. In C, doing idiomatic C, I would not run into any issues because I would just have used strftime and never had to look at a tm struct at all.

In Javascript, trying to do idiomatic Javascript, all those things are exposed. It's an API problem.

5

u/itsnotlupus beep boop May 29 '13

The cool way to deal with date formatting issue is this:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat

Disclaimer: Your browser is probably not cool enough to use it yet.

But if you had a cool browser, you could do this:

var dtf = new Intl.DateTimeFormat("fr-FR", {year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric" })

dtf.format(new Date()) // "29/5/2013 15:45"

var dtf = new Intl.DateTimeFormat("en-US", {year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric" })

dtf.format(new Date()) // "5/29/2013 3:45 PM"

Wouldya just look at that.

2

u/ralsina May 29 '13

Oh, cute! Me wants!

15

u/Knotix May 29 '13

I kindly direct you to Moment.js

6

u/ralsina May 29 '13

Does it make sense to add 5.5KB of minified JS to avoid one ugly line?

12

u/cwmma May 29 '13

Yes

5

u/ralsina May 29 '13

Why?

8

u/ugoagogo May 29 '13

Cross browser parsing of ISO-8601 and easy, multilingual pretty date formatting

1

u/ralsina May 29 '13

But I only need date formatting once, in one specific format.

5

u/actionscripted May 29 '13

It's only an extra 5K

-3

u/ralsina May 29 '13

It's either a whole chunk of ungodly minified JS in my template or a separate request, too.

0

u/[deleted] May 29 '13

[deleted]

5

u/sweetbeej May 29 '13

Moment does other things that you won't realize until later. Get a time and date, add one hour to it for lets say 1 years worth of hours. When your loop is done you will notice that your date object has not advanced to oldDate + 8766 hours (1 year). Why is this? Apparently it's not safe to advance a datetime one hour in certain situations? well a little something called daylight savings my friend.... It might work fine if you live in a country or state that doesn't have daylight savings (Arizona or China for example). This just works in Moment.js plus you get all sorts of other nifty things.

1

u/ralsina May 29 '13

I am sure there are many, many libraries that do lots of other cool stuff I don't need right now, should I use them too? :-)

3

u/Knotix May 29 '13

No one is saying you must include this library, but it's a very safe option especially when dealing with the use-cases listed. It will also come in handy when you have to deal with user-entered dates.

3

u/octatone May 29 '13

Good luck with your l18n then ...

-4

u/ralsina May 29 '13

Thanks (although I suspect you meant l10n ;-)! This is an internal representation. It's silly to localize it.

1

u/octatone May 29 '13

I mean I18n, mixed it with L10n lol

0

u/ralsina May 29 '13

I think date formatting is localization, not internationalization, IIRC but tomato, tomahto :-)

2

u/cwmma May 29 '13

See my other comment

13

u/Knotix May 29 '13 edited May 29 '13

It's useful if you support multiple regional formats or need to do date manipulation without worrying about leap years or how many days are in each month. Don't get me started on handling user-entered dates.

I find 5.5kb to be negligible.

10

u/a-t-k Frontend Engineer May 29 '13

While JavaScript comes without most of the "batteries included" stuff in other languages, there are usually simple ways to achieve the desired results:

(new Date()).toISOString().replace(/^(\d+).(\d+).(\d+)T(\d+:\d+).*/, "$3/$2/$1 $4")

may not be beautiful, but it gets the job done. That's JavaScript for me. It gets the job done. So don't cry, but instead try to figure out the easiest way to get the job done.

-7

u/ralsina May 29 '13

Your proposed solution, while clever, is considerably uglier than even what made me write the post (but hey, it gets the zero-padding right).

You are assigning merit in the wrong place. Javascript is not getting the job done. You are. Despite, I must say, Javascript's best efforts to not let you do it.

4

u/a-t-k Frontend Engineer May 29 '13

I don't think that JavaScript is actually making any effort not to let one achieve one's goals, unless the goal is to write code as if in any other modern scripting languages with a full set of libraries at one's disposal. Type coercion can produce evil bugs as well as powerful code. Prototypal Object Orientation may look ugly to those who are accustomed to class inheritance, but it works if used as intended. Browser inconsistencies can be a bitch, but at least all modern browsers have them mostly fixed. Most modern HTML5 APIs are cool as fuck. And if you're out of luck, take a look at the source of those external libraries. Most times, you can snatch a few lines of code from there to get your job done.

If you intend to prevail in JavaScript development, you may want to adopt the dictum: "if it's stupid, but works, it's not stupid".

1

u/ralsina May 29 '13

The problem described doesn't need any libraries. In fact, the most frequently proposed solution is to add 3rd party libraries!

The obvious solution is to have a String class that can do formatting and/or string interpolation, or a Date class that has some sort of equivalent of strftime in addition to the NINE methods it already has that produce one different string format each (toLocaleString, toString, toGMTString, toISOString, toLocaleDateString, toLocaleTimeString, toDateString, toTimeString, toUTCString).

I have no intention whatsoever of becoming a "real" Javascript developer if it's at all possible to avoid it, though, but I accept as a fact of life that I have to write some every now and then.

6

u/[deleted] May 29 '13

Are you sure the problem described even exists?

Glancing at your code it looks like you're using django-datetime-widget which has date formatting functionality you can use. Not to mention that it looks like you're using templating to fill in stuff like the user's name so it's trivial to prepopulate the date field with {% now some_format_string %}.

1

u/ralsina May 29 '13

You are right! I never thought of formatting the current datetime serverside and stuffing it in the template. Good idea :-)

1

u/[deleted] May 29 '13

For the record, I think you have a good underlying point - JS lacks the "batteries included" feel of some other languages and it can be frustrating/painful. I just don't think this is a great example. I'd also say it's something that can be beneficial at times as it lets you choose functionality a la carte.

2

u/deralte May 29 '13

Most modern HTML5 APIs are cool as fuck.

They seem that way only because before they sucked horribly.

1

u/a-t-k Frontend Engineer May 30 '13

Some APIs like the XMLHttpRequest behave incredibly nice considering the age.

4

u/[deleted] May 29 '13

To be fair what you're doing is rather unusual. The client side time is unreliable so you don't very often want to use it as data in a web app. If you're trying to store when the form is submitted you would use the server-side time. If you're storing some arbitrary date like the last time the user went shopping for socks you probably still wouldn't want to rely on the client side time, even for prepopulating.

For the times when you're ok with it, I agree some more functionality would be nice but you can write a function to do what you need in a couple lines and be done with it.

-2

u/ralsina May 29 '13

It's the date/time of a blog post. Anything "now-ish" is good as an initial value, but it does need to be editable by the user.

Good point about the reliability, thanks!

2

u/[deleted] May 29 '13

Is it really that common to want to set the date/time of a blog post to something other than the current time? I'd optimize for the common case, the date can always be changed in the "edit post" option.

-1

u/ralsina May 29 '13

Yes, for delayed posting, it turned out to be a commonly requested feature. Besides the post creation and post editing forms are the same form so far ;-)

1

u/[deleted] May 29 '13

If it's for delayed posting you're going to want to base it on a more precise format and the server time. With that and the fact that it's a plain text input you're going to get into more formatting/validation anyway so a library might not be a bad idea.

Besides the post creation and post editing forms are the same form so far ;-)

Right, you wouldn't need to create a whole new form.

It sounds like you're going for something more fully featured, which naturall will require more code to support.

-1

u/ralsina May 29 '13

Actually the entry is not editable directly, it's only editable via a JS date/time picker, and it's validated client and server-side.

The only missing bit was setting the starting date.

3

u/[deleted] May 29 '13

If you're using a datepicker, you shouldn't be hitting the issue described in the OP. A good date picker will handle setting and/or formatting the date picked.

At any rate it's moot. If you want to avoid all sorts of issues with wrong client times, posting from different computers, etc you should base all the calculations on the server time; formatting it as appropriately (to appropriate time zone, etc) for the client then back for calculations.

I feel for you, dealing with dates is huge PITA and yes JS doesn't make it any easier for you.

1

u/gotnate May 30 '13

from experience with the jquery-ui date picker, it is browser dependent how it defaults. IE likes to start at 0000-00-00 00:00:00 for example. To work around it, I always seed it from PHP rather than javascript.

2

u/x-skeww May 29 '13

Usually, when it comes to blog posts and things like that, the date field is optional. If left empty, the current time is used. There is no need to use JavaScript for that.

1

u/ralsina May 29 '13

Which is why I pre-fill the field with the current time. I'd rather be explicit and show it instead of relying on empty fields, but that's just my taste.

4

u/x-skeww May 29 '13

Which is why I pre-fill the field with the current time.

That's the time when the page was loaded, not the time when the post was submitted.

Using the empty=now pattern doesn't automatically mean that it's magic behavior. You can tell the user how it works. Drupal does it that way, for example.

0

u/ralsina May 29 '13

Again, it's a matter of personal taste. I prefer showing something instead of explaining what it means not to show it.

1

u/x-skeww May 29 '13

I prefer showing something

I prefer correct data. I wouldn't refer to this as "taste".

In the past I spent up to 20 hours on a single article. That's the kind of drift you're adding there.

If you want to be explicit, add a "now" button which populates the field with the current time.

1

u/ralsina May 29 '13

I could animate the date/time :-)

There's a date picker, clicking on it by default gets you the current date/time.

2

u/[deleted] May 29 '13

The problem with getDay vs getDate: date at WordNet or to save you the click:

date
    n 1: the specified day of the month; "what is the date today?"
    [syn: date, day of the month]

( getDayOfTheMonth() is a bit annoying to write every time ;) )

1

u/ralsina May 29 '13

Date also means "Time stated in terms of the day, month, and year." according to the first dictionary I found googling) but yes, by that definition getDate's name is not a lie, thanks!

It would make more sense IMHO to use getDay() [or getDays() if you want to be consistent with getMinutes/getHours] and getWeekDay() which makes the less frequent request get the longest function name, and is the convention used in, for example, python.

3

u/kenman May 29 '13 edited May 29 '13

Don't know what to tell you, other than "sorry that Javascript isn't Java".

edit: in reply to your update...

I refuse to accept as reasonable that the Javascript creators looked at the C stdlib and decided it was a good idea to expose "months are 0-based" and "years are 1900-offset" and not strftime and sprintf.

I'd just like to point out that it wasn't "creators", it was a lone creator. And he didn't exactly sit down and spend a whole lot of time on the details, he was working under time constraints. He knew it wasn't perfect then, he knows it's not perfect now, as most of us here acknowledge that it isn't perfect. However, crying about it (your words) isn't productive. We can all sit around and bitch & moan, but that alone doesn't get stuff done.

Writing a library to handle it yourself or drafting an RFC & getting involved in the ECMA committee are both productive. Sitting here and railing against things that have been like this for eons isn't really doing anyone a service, though. Perhaps you were aiming for education, but instead ended up with a rant.

1

u/ralsina May 29 '13 edited May 29 '13

I don't know what to tell you, other than "Java, really?" ;-)

1

u/kenman May 29 '13

I edited my comment in response to your editing of the page :)

0

u/ralsina May 29 '13

As you can see, I made it work, then ranted. That's the proper order!

Yes, I suppose I could get into the ECMA comittee (well, not really) but is there nothing in the middle, between "suffer in silence" and "become part of a language design bureaucracy"?

I say there is, and that ranting about obvious, clear shortcomings is good in itself, because it makes it abundantly clear to anyone who reads it that it is, indeed crap. And pointing at crap and saying "lookout! crap there!" is an important service, both in sidewalks and in life.

Also, yes, single creator with time constraints... in the 90s. It has had almost 20 years to get Date and String into usefulness.

2

u/dagingaa May 29 '13

Well, Java has a pretty shite DateTime library in itself (JodaTime does not count), so it isn't much better. Look at Ruby, Perl and Python for beautiful DateTime-handling.

4

u/Enumerable_any May 29 '13

Ruby's DateTime library is far from beautiful.

Time.new(2013, 2, 2).to_s # => "2013-02-02 00:00:00 +0100"
DateTime.new(2013, 2, 2).to_s # => "2013-02-02T00:00:00+00:00"

not only do they output the time in different formats, Time is also time zone aware while DateTime is not.

1

u/[deleted] May 29 '13

Ironically JS's Date object was based on java.util.Date, so for once it sort of is.

9

u/ezekelol May 29 '13

I totally understand your frustration with this particular aspect of Javascript; but please bear in mind that the language was never intended to become this popular. Luckily it's quite easy to extend it so you can make use of other libs such as Moment.js (even though that means loading another 5,5kb)

1

u/Rainbowlemon May 31 '13

Am I missing something here? Can you not just do...

var d = new Date();
var date = d.toLocaleDateString() + ' ' + d.toLocaleTimeString();

As long as it's being validated server-side, I don't see there being an issue...

1

u/ralsina Jun 03 '13

Yes, you are missing that the output of that is locale-dependent :-)

1

u/Rainbowlemon Jun 03 '13

Yeah... surely that's what you'd want?

1

u/ralsina Aug 01 '13

Not necessarily.

1

u/cwmma May 29 '13 edited May 29 '13

JavaScript doesn't have a much of a standard library, this is why every single website (more or less) uses jQuery and/or underscore. I really feel like moment is quickly becoming the javascript version of the python DateTime, except optional, and improving rapidly.

1

u/LukaLightBringer May 29 '13

The reason sites use JQuery is that the dom implementation is hard to work with and inconsistent among different browsers.

1

u/cwmma May 29 '13

I know Ajax is the other big one

-1

u/ralsina May 29 '13

In this case though, the Date class already exists, it's just incomplete, and this is a very limited usage I needed, which can be worked around with straightforward (but ugly) code, so I don't see a benefit that outweighs "yet another 3rd party JS file I have to track, ship and load"

I am using jQuery in this site already, I often wish it came with a minimally functional string class, at least.

1

u/bishopZ May 29 '13

You should checkout Typecastjs.org. It is made to help work out problems like this.

3

u/ralsina May 29 '13

I'll take a look, thanks!

1

u/mattfoster01 May 29 '13

I think the consensus is Javascript has a ton of shortcomings, that's why there are so many libraries to alleviate these issues.

Date isn't even close to the worst part, at least it's browser consistant. But I suppose the rant wagon for the DOM is loaded so here we are talking about Date and how frustrated you are it didn't do what you wanted.

0

u/ralsina May 29 '13

Yes, pretty much. Well, except for the chorus of "it doesn't matter that Date is crap!" and "use this other thing instead!"

1

u/mattfoster01 May 29 '13

There's always VBScript, I'm sure that has better date methods.

1

u/ralsina May 29 '13

Wouldn't surprise me. Now what does that say about Javascript? ;-)

0

u/mattfoster01 May 29 '13

That you should stop using it, it's obviously beneath you

1

u/ralsina May 29 '13

I use Javascript when I have to, and I clean up after my cat, I am just blue collar that way.

1

u/mattfoster01 May 29 '13

Do you complain this much about cat shit too?

1

u/ralsina May 29 '13

Well, if I built cats, I could surely think of some improvements!

1

u/mattfoster01 May 29 '13

And you didn't build the ECMA engine either. The bottom line is, take momentjs or another date library and run with that, otherwise deal with the hurdles of the native Date object.

2

u/ralsina May 29 '13

So, stay quiet and bear it, or use this and shut up.

That's a really bad attitude, which I find sadly prevalent in JS and PHP developers. It does help explain how crappy the Date and String interfaces have remained for so long.

→ More replies (0)

1

u/[deleted] May 29 '13

Write a little function to do this for you, and stick it in your toolkit.

1

u/[deleted] May 29 '13

woosh

0

u/[deleted] May 29 '13

[deleted]

0

u/ralsina May 29 '13

The standard in "Standard Library" is there for a reason :-)

Also, strtotime is exactly the opposite use case.

0

u/[deleted] May 30 '13

[deleted]

0

u/ralsina May 30 '13

Except the cost of tracking updates and deployment is borne by the developer, half the time it leads to fragmentation, and the broken and incomplete stuff that actually is part of the language is not improved, of course.

0

u/[deleted] May 30 '13

[deleted]

0

u/ralsina May 30 '13

Like I said perhaps 4 times, if I see that I need several date/time operations, I'm all for it.