views:

36

answers:

3

How I can format a date string using Javascript. For example:

var date_str = "2010-10-06T03:39:41+0000";

The result should be like this:

11:39 AM Oct 6th

Is there any ideas on this? Note: date_str is an example of returned date from Facebook Graph API.

Thanks in advance.

A: 

Hi,

Use this function from phpjs.org: http://phpjs.org/functions/date:380

Adam Wallner
date(format, timestamp) is ok but the problem is how to convert the date_str to timestamp so that i can pass it to the function.
Trez
Sorry, this is your function: http://phpjs.org/functions/strtotime:554
Adam Wallner
Thanks for the suggestion...
Trez
A: 

Date.parse can parse this if you strip the +0000 part. You can then use setTime on a Date object, which you can pretty print yourself, or using some library.

Erik Hesselink
+1  A: 

Parsing the date shouldn't be too difficult - all the components are in the right order so you just need to split on the special characters, subtract 1 from the month value and apply the array, minus the last element, to Date.UTC():

function parseDate(dStr) {
    var d    = dStr.split(/[-:T+]/); d[1] -= 1; d.pop();
    var date = new Date(Date.UTC.apply(Date, d));

This gives us a Date object for the date specified, the rest is just formatting each component back into a string:

    // Declare an array of short month names
    var mon  = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov", "Dec"];
    // Determine between AM and PM
        ampm = date.getHours() > 12 ? "PM" : "AM",

    // Prepare for working out the date suffix
        nth  = date.getDate();

    // Date is nth for 11th, 12th and 13th
    if (nth >= 11 && nth <= 13)
        nth = "th";
    // Otherwise it's st, nd, rd, th if the date ends in 1, 2, 3 or anything else
    else
        nth  = ["", "st", "nd", "rd"][(nth+"").slice(-1)] || "th";

    // Return the string formatted date
    return (date.getHours() % 12) + ":" + (date.getMinutes()) + " " + ampm +
           " " + mon[date.getMonth()] + " " + date.getDate() + nth;
}

// Example:
parseDate("2010-10-06T03:39:41+0000");
// -> "4:39 AM Oct 6th" (in my timezone)

If you want the output to be the same regardless of timezone (the original time supplied), you need to swap the methods getHours(), getMinutes(), etc for getUTCHours(), getUTCMinutes(), etc.

Andy E
Awesome... A lot of thanks Sir!...
Trez
@Trez: I noticed a small error with the date suffix part, I've fixed it now. Hopefully you'll see this before you go ahead and implement the solution :-)
Andy E
Got it... Thank you!
Trez