0

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?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
cvsguimaraes
  • 12,910
  • 9
  • 49
  • 73
  • 3
    You don't need a regex to parse the date string, just ask the date object for the year, month, day, etc. See [this question](http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript) for more info. Also, check out [Datejs](http://www.datejs.com/). – gen_Eric Aug 30 '11 at 14:55
  • 3
    `var output = "MMM DD YYYY hh:mm";` \*ducks\* – Lightness Races in Orbit Aug 30 '11 at 14:57
  • If I'm grabbing said date from a database like SharePoint, \*hits the dirt inside a premade Fallout vault* and it is in format yyyy-dd-MM HH:mm:ss:SSSS, which of these solutions is going to work best? – HadesHerald Jul 07 '15 at 22:12

4 Answers4

3

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
Mrchief
  • 75,126
  • 20
  • 142
  • 189
2

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

fbstj
  • 1,684
  • 1
  • 16
  • 22
2

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');
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
1

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

Joao Costa
  • 2,563
  • 1
  • 21
  • 15