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?

3
  • 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 for more info. Also, check out Datejs. Commented Aug 30, 2011 at 14:55
  • 3
    var output = "MMM DD YYYY hh:mm"; *ducks* Commented Aug 30, 2011 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? Commented Jul 7, 2015 at 22:12

4 Answers 4

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 
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.