Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Date Conversion milliseconds to month, date, year

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)?

like image 391
Jordan.J.D Avatar asked Oct 16 '25 02:10

Jordan.J.D


2 Answers

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/

like image 101
Cameron Tinker Avatar answered Oct 17 '25 16:10

Cameron Tinker


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
like image 26
Matt Avatar answered Oct 17 '25 14:10

Matt