JavaScript date string formatting

Posted on 15th of July 2008

Date string formatting is very brutal in JavaScript, which probably has the worst built in library in relation to the distribution this language sees. So a long time ago I whipped up a script file, for doing just this. I always though PHP’s date function looked very nice, so I decided to model my function upon that.

Download: formatDate.js (13kB)

Supported switches and test

I’m not going to duplicate PHP’s documentation. But I will list briefly the supported switches. Basicly, switches should return the same as in PHP, if they don’t, it’s most likely in error, so let me know at .

Supported switches Unsupported switches Currently unsupported, but might be included in the future
a, A, B, c, d, D, F, g, G, h, H, i, I (uppercase i), j, l (lowecase L), L, m, M, n, N, O, P, r, s, S, t, U, w, W, y, Y, z, Z T, e, o

Here’s some examples.

Example Output
F j, Y, g:i a
m.d.y
j, n, Y
Ymd
h-i-s, j-m-y, it is w Day z
%i%t %i%s %t%h%e jS %d%a%y.
D M j G:i:s T Y
H:m:s %m %i%s% %m%o%n%t%h
H:i:s

And here you can test your own flags if you should wish.

output:

Differences and gotchas

You should note quite quickly that you use % to escape, not backslash (\). PHP gets to treat strings a bit different, and frankly, \\d\\u\\m\\b looks stupid (not to mention the quadruple escape, \\\\, if you want a single backslash in your output).

Another thing to note is that this code operates either directly on a Date object (which always have a time set), or a passed in value, which it interprets as a date. The script doesn’t help you in any way in setting a time. As a developer, you need to be careful when juggling dates on the client side, and also if you create any dates, don’t make assumptions regarding what timezone the runtime thinks it is.

I’ve obsoleted my old page, though it’s still on the site under a different name. It had some more rigerous testing (it’s using the old version of the script so take care), and also some stuff about localization which I don’t really think is that interesting anyway.

Tags: , ,

5 Responses to “JavaScript date string formatting”

  1. Rob S. Says:

    Thanks Svend! Great script, really handy.

    Rob

  2. Adrian Thurley Says:

    Hi Svend! I am trying to get code to input the specific date wit todays date in the Java script: FSfncWriteFieldHTML(”DateForm”,”ArrDate”,”None”,100,”FutureShockDateSelector/images/FSdateSelector/”,”EN”,”true”,”true”, “19/07,2008″)

    I am fairly new to Java. Do I just add your script in the head of the page and then just enter “d/m,Y” in the other script? Can’t be that easy is it?

    Great site by the way.

  3. svendtofte Says:

    FSfncWriteFieldHTML seems to be a product that creates a date selector control for your form. My little script merely formats dates, they are not related.

  4. Howard Chen Says:

    Thanks!

    Very nice script!

  5. Phil Says:

    Dômo svend. Script ha totemô î desu, yo!

Leave a Reply