4

I am trying to convert milliseconds into a date that looks like: Oct 04, 2013. I converted milliseconds into a date object with:

var d1 = new Date(milliseconds);

which then outputs something like:

Fri Oct 04 2013 13:59:31 GMT-0400 (Eastern Daylight Time)

If I use getMonth() , getDate(), and getFullYear() the output becomes 9 4 2013

How do I get the month either a full name (October) or shortened to three characters (Oct)?

Jordan.J.D
  • 7,999
  • 11
  • 48
  • 78

4 Answers4

6

Please take a look at Moment.js. It provides all date conversions that you could possibly need.

With Moment.js, you would do this:

moment(milliseconds).format('MMM DD, YYYY');

Here is a full format table for use with moment objects: http://momentjs.com/docs/#/displaying/format/

Cameron Tinker
  • 9,634
  • 10
  • 46
  • 85
4

If you do not want to use a library, one solution to showing 'written' months would be to create an array containing all month names:

var monthName = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
                 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

From there, you can use this array to display the month name in a string:

var d1 = new Date(milliseconds),
    d = d1.getDate(),
    m = d1.getMonth(),
    y = d1.getFullYear();

var dateString = monthName[m] + " " + d + " " + y; // Oct 4 2013
Matt
  • 3,079
  • 4
  • 30
  • 36
2

Months in javascript start at zero so getMonth() on a February date will return 1 for example.

Mike Cheel
  • 12,626
  • 10
  • 72
  • 101
1

The best choice would be d1.toDateString(). Other than that there is no StringFormat for Dates in JavaScript.

phylax
  • 2,034
  • 14
  • 13