user1633440
user1633440

Reputation:

How to convert milliseconds to a date string?

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?

Upvotes: 9

Views: 31578

Answers (1)

Eliran Malka
Eliran Malka

Reputation: 16283

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

Upvotes: 24

Related Questions