Reputation: 8113
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)?
Upvotes: 4
Views: 15884
Reputation: 3120
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
Upvotes: 4
Reputation: 9789
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/
Upvotes: 6
Reputation: 2086
The best choice would be d1.toDateString()
.
Other than that there is no StringFormat for Dates in JavaScript.
Upvotes: 1
Reputation: 13106
Months in javascript start at zero so getMonth() on a February date will return 1 for example.
Upvotes: 2