views:

41

answers:

2

Hi,

I have the following date format: 2010-04-15 23:59:59

How would I go about converting this into: 15th Apr 2010

using javascript

+3  A: 

Check out Datejs. You'll probably want to parse your timestamp and then call toString('MMS MMM yyyy') (or something to that effect) on it. Here's some more info on toString.

There's probably a more-lightweight solution, if this is all you're after.

dylanfm
+1  A: 

Like dylanfm suggests, I would check out Datejs, but if you only want to convert the way you are describing, this might work for you:

 var m = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
 var p = ["th","st","nd","rd"];

 // create date object - have to replace dashes with slashes
 var d = new Date("2010-04-15 23:59:59".replace(/-/g,"/"));

 // index in array p based on date % 10
 var pn = d.getDate() % 10;

 // pick "th" for days 11-13
 if (d.getDate() > 10 && d.getDate() < 14 ) pn = 0;

 // pick "th" for days 4-9, 14-19, 24-29
 if (pn >= p.length) pn = 0;

 // date in format "15th Apr 2010"
 var formatted = d.getDate() + p[pn] + " " + m[d.getMonth()] + " " + d.getFullYear();

Note that this is nowhere near as flexible as using a library like Datejs.

Mario Menger