问题
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