cvsguimaraes
cvsguimaraes

Reputation: 13260

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?

Upvotes: 0

Views: 3664

Answers (4)

Joao Costa
Joao Costa

Reputation: 2863

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

Upvotes: 1

Mrchief
Mrchief

Reputation: 76268

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

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227310

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');

Upvotes: 2

fbstj
fbstj

Reputation: 1714

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

Upvotes: 2

Related Questions