开发者

Formatting a date for output

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 t开发者_如何学Chis? Note: date_str is an example of returned date from Facebook Graph API.

Thanks in advance.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜