Coder Perfect

In JavaScript, convert a Unix timestamp to time.

Problem

I’m storing time as a Unix timestamp in a MySQL database and sending it to some JavaScript code. I’m not sure how I’d get quite the right amount of time out of it.

In HH/MM/SS format, for example.

Asked by roflwaffle

Solution #1

Please see MDN or the ECMAScript 5 specification for further details on the Date object.

Answered by Aron Rotteveel

Solution #2

Answered by shomrat

Solution #3

Because JavaScript runs in milliseconds, you’ll need to convert the UNIX timestamp to milliseconds first.

var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...

Answered by Steve Harrison

Solution #4

Use:

var s = new Date(1504095567183).toLocaleDateString("en-US")
console.log(s)
// expected output "8/30/2017"  

and for time:

var s = new Date(1504095567183).toLocaleTimeString("en-US")
console.log(s)
// expected output "3:19:27 PM"

see Date.prototype.toLocaleDateString()

Answered by Dan Alboteanu

Solution #5

In the new world, we should be moving towards the standard Intl JavaScript object, that has a handy DateTimeFormat constructor with .format() method:

But to be 100% compatible with all legacy JavaScript engines, here is the shortest one-liner solution to format seconds as hh:mm:ss:

This method is compatible with all browsers and JavaScript engines and does not require any third-party libraries.

Answered by VisioN

Post is based on https://stackoverflow.com/questions/847185/convert-a-unix-timestamp-to-time-in-javascript