0

I am working towards formatting my date and time from MON APR 08 2013 00:00:00 GMT-0400 (EASTERN DAYLIGHT TIME) to look like MON APR 08 2013 01:01:01. Although I am having no luck with everything I have tried. Can someone shed a little light. Below is the last piece of code I have tried. Thanks.

var date = new Date(parseInt(data[0].published.substr(6)));
var time = new Date(date.toLocaleDateString());
Chris Baker
  • 49,926
  • 12
  • 96
  • 115
jpavlov
  • 2,215
  • 9
  • 43
  • 58

2 Answers2

1

If you can, the best practice would probably be to format the date server-side, or at least present a more universally useful date (like a UNIX timestamp) instead of the formatted string.

However, if changing the server-side output is not an option, you can use the javascript date object. I see you've tried that, but you're not using the date object's constructor properly:

var dateString = 'MON APR 08 2013 00:00:00 GMT-0400 (EASTERN DAYLIGHT TIME)';
var dte = new Date(dateString);
document.write(dte.toDateString()); // output: Mon Apr 08 2013

Try it: http://jsfiddle.net/BvLkq/

If you need to reconstruct the time, you can use toLocaleDateString (docs) to pass a locale or format string, or you can build one up by hand using the getHours() (etc) functions .

Documentation

Chris Baker
  • 49,926
  • 12
  • 96
  • 115
  • var time = date.localeFormat("dddd, MMMM d yyyy, h:mm:ss"); – jpavlov Aug 13 '13 at 18:05
  • that ended up working from me, i was reformatting from a json file and the text came out strange. thanks. – jpavlov Aug 13 '13 at 18:06
  • `localeFormat` is a non-standard method, though. Mozilla U/A implements a related-but-different non-standard method, too. There IS, however, a standardized method called `toLocaleDateString`, which has a complex format argument that **might** get the job done in a standard way. Otherwise, there is http://momentjs.com/, which is a lightweight library that provides more sophisticated (and standardized!) date format options. Glad I was able to help -- I've edited my answer to include a bit about `toLocaleDateString ` :) – Chris Baker Aug 13 '13 at 20:15
0

Just use a simple regex.

var str = 'MON APR 08 2013 00:00:00 GMT-0400 (EASTERN DAYLIGHT TIME)';
console.log(str.replace(/(.*\d{2}\:\d{2}\:\d{2}).*$/, '$1'));
// outputs MON APR 08 2013 00:00:00
ryan
  • 6,541
  • 5
  • 43
  • 68