0

Just wondering how I would format a javascript date to be like

yearmmddThhmm

20130511T0825
superlogical
  • 14,332
  • 9
  • 66
  • 76

2 Answers2

3

The best thing I've found for formatting dates in JS (aside from painstakingly putting the pieces together) is using momentjs. It is lightweight and the API is super simple. Just give it a date object, pass it a few parameters, and bam, get your nicely formatted date back.

imjared
  • 19,492
  • 4
  • 49
  • 72
2

Date has toISOString, which is almost there, then just strip out what you don't want.

var d = new Date(), // Tue Jun 04 2013 21:23:52 GMT+0100 (GMT Daylight Time)
    s = d.toISOString(); // "2013-06-04T20:23:52.058Z"
s.replace(/[^\da-z]/ig, '').slice(0, -6); // 20130604T2023"
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • 1
    Interesting approach… yet you would need to `.slice(0, -6)` to get the desired output with hours and minutes only. Assuming the browser implements `toISOString` correctly at least… – Bergi Jun 04 '13 at 20:27
  • Need to go a little further back to strip out the seconds if you want to do that, but this is harder to read and harder to change if necessary if the requirement changes. I'd suggest something like moment.js as suggested below if any more date stuff is being done. – Colin DeClue Jun 04 '13 at 20:28