Rue Vitale
Rue Vitale

Reputation: 1891

How do i convert a timestamp string into a date?

I have the following string "1576354589.222591". How can I covert it into a date?

I tried new Date(1576354589.222591).toLocaleString() but that does not work. It gives me 1/8/1970

Upvotes: 1

Views: 643

Answers (3)

Arpit Bhatia
Arpit Bhatia

Reputation: 173

It can be done by using

new Date(1576354589.222591*1000).toLocaleString()

and another alternative approach can be done by using moment.js

In case if you want to use here is the documentation link https://momentjs.com/guides/

Check out the code below in snippet.

console.log(moment(1576354589.222591).format("DD MMM YYYY hh:mm a"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>

Upvotes: 0

Raeesh Alam
Raeesh Alam

Reputation: 3480

Timestamp is in milliseconds so need to multiply by 1000 to convernt into seconds. By below snippet you can find date+time or only date or only time.

var Date_and_Time = new Date(1576354589.222591*1000).toLocaleString();
var Only_Date = new Date(1576354589.222591*1000).toLocaleDateString();
var Only_Time = new Date(1576354589.222591*1000).toLocaleTimeString();

console.log('Date and Time: '+Date_and_Time);
console.log('Only Date: '+Only_Date);
console.log('Only Time: '+Only_Time);

Upvotes: 1

DWilches
DWilches

Reputation: 23016

Date expects the date in milliseconds, not seconds, so multiply the value by 1000:

new Date(1576354589.222591*1000).toLocaleString()

yields:

"12/14/2019, 12:16:29 PM"

Upvotes: 2

Related Questions