Skip to content Skip to sidebar Skip to footer

Reformatting Date String

Given input like 'Tue Aug 30 2011 11:47:14 GMT-0300', I would like output like 'MMM DD YYYY hh:mm'. What is an easy way to do it in JavaScript?

Solution 1:

Via JS, you can try converting it to a date object and then extract the relevant bits and use them:

var d = new Date ("Tue Aug 30 2011 11:47:14 GMT-0300")
d.getMonth(); // gives you 7, so you need to translate that

To ease it off, you can use a library like date-js

Via regex:

/[a-zA-Z]{3} ([a-zA-Z]{3} \d{2} \d{4} \d{2}:\d{2})/ should do the trick.

var r = "Tue Aug 30 2011 11:47:14 GMT-0300".match(/^[a-zA-Z]{3} ([a-zA-Z]{3} \d{2} \d{4} \d{2}:\d{2})/);
alert(r[1]);   // gives you Aug 30 2011 11:47

Solution 2:

check out Date.parse which parses strings into UNIX timestamps and then you can format it as you like.


Solution 3:

If you don't mind using a library, use Datejs. With Datejs, you can do:

new Date ("Tue Aug 30 2011 11:47:14 GMT-0300").toString('MMM dd yyyy hh:mm');

Solution 4:

A sample function:

function parseDate(d) {
    var m_names = new Array("Jan", "Feb", "Mar", 
                    "Apr", "May", "Jun", "Jul", "Aug", "Sep", 
                    "Oct", "Nov", "Dec");

    var curr_day = d.getDate();
    var curr_hours = d.getHours();
    var curr_minutes = d.getMinutes();

    if (curr_day < 10) {
        curr_day = '0' + curr_day;
    }
    if (curr_hours < 10) {
        curr_hours = '0' + curr_hours;
    }
    if (curr_minutes < 10) {
        curr_minutes = '0' + curr_minutes;
    }

    return ( m_names[d.getMonth()] + ' ' + curr_day + ' ' + d.getFullYear() + ' ' + curr_hours + ':' + curr_minutes);
}


alert(parseDate(new Date()));

Or have a look at http://blog.stevenlevithan.com/archives/date-time-format for a more generic date formatting function


Post a Comment for "Reformatting Date String"