最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Date Conversion milliseconds to month, date, year - Stack Overflow

programmeradmin4浏览0评论

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 bees 9 4 2013

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

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 bees 9 4 2013

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

Share Improve this question asked Apr 4, 2014 at 18:02 Jordan.J.DJordan.J.D 8,11311 gold badges50 silver badges79 bronze badges 2
  • 4 get month names from date – Will N Commented Apr 4, 2014 at 18:05
  • 2 Either create your own lookup table or find a date library. – Jasen Commented Apr 4, 2014 at 18:07
Add a ment  | 

4 Answers 4

Reset to default 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./docs/#/displaying/format/

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

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

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

发布评论

评论列表(0)

  1. 暂无评论