How to convert milliseconds to a date string?

社会主义新天地 提交于 2020-01-03 20:05:01

问题


I get a miliseconds string from the server like this: 1345623261.

How can i convert this into a normal date format, e.g. 30.08.2012?

I attempted using setMilliseconds, like so:

new Date().setMilliseconds(time_posted).toLocaleString();

But this doesn't work. How to do that?


回答1:


Assuming time_posted is a number representing timestamp, which is expressed in seconds (judging by the number of digits) - multiply it by 1000 to get a representation in milliseconds, and pass the result to the Date's constructor:

(new Date(time_posted * 1000)).toLocaleString();
    // -> "Wed Aug 22 2012 11:14:21 GMT+0300 (Jerusalem Daylight Time)"

To take this a bit further and achieve something closer to what you denoted in the question, use toLocaleDateString(), which will produce a more human-readable form:

(new Date(time_posted * 1000)).toLocaleDateString();
    // -> "Wednesday, August 22, 2012"

Reference

  • Date on Mozilla Developer Network


来源:https://stackoverflow.com/questions/12196689/how-to-convert-milliseconds-to-a-date-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!