Sunday 19 April 2009

Sharing my Javascript toolbox - Date Formatting

I was sorting out my Javascript Utilities into some semblance of order over the weekend and I found an extension to the date object that you might find useful. This is one of those things that I use on a daily basis and kinda forget that it is not standard and that other people may find it useful.

Basically what I got pissed off having to recode date formatting routines and having to remember things like how to work out the week number in the year given a data. So I extended the native Date Object with a new method called format which if you supply it with a date format string will return the date in the format you require. Rather like the format() LS command. However being a bit of a PHP nut I used the PHP format string structure as my starting point, because it makes more sense (well to me anyway... and i am very odd)

The format string you use can be made up of the following characters.
All other characters and spaces in your string will be considered as constants., but be careful of including words like "and" which will be resolved as "a", "n", "d"

When you add my code to your web pages/forms all you need to do is instansiate your date and then use the new method format([format string],[locale code]) and the date stored in your Date object will be returned in the format you requested For example
myDate = new Date();
xxx =myDate.format("d/m/Y","EN")
Will result in xxx containing 19/04/2009 or
myDate = new Date();
xxx = myDate.format("D dS, F Y","EN")
will result in xxx containing Sunday 19th, April 2009


I have provided 3 Locale's English =EN, French =FR, and German = DE however it is really easy to add others if you need them. In the code find the definition for

daysL = Names of Days Long
daysS = Names of Days Short
monthL = Names of Months Long
monthS = Names of Months Short
daySuf = Suffices for Day numbers (st,nd,rd and th)

and add the values that you want in the format that the other countries are in.

You can get the JS source code DateExt.js here feel free to use and if you find anything odd, wrong or additions that you find useful please let me know ... enjoy ;-)

Disqus for Domi-No-Yes-Maybe