Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Unix timestamp to time in JavaScript

I am storing time in a MySQL database as a Unix timestamp and that gets sent to some JavaScript code. How would I get just the time out of it?

For example, in HH/MM/SS format.

like image 983
roflwaffle Avatar asked May 11 '09 08:05

roflwaffle


People also ask

How do you convert timestamps to time?

UNIX timestamps can be converted to time using 2 approaches: Method 1: Using the toUTCString() method: As JavaScript works in milliseconds, it is necessary to convert the time into milliseconds by multiplying it by 1000 before converting it. This value is then given to the Date() function to create a new Date object.

What is a UNIX timestamp JavaScript?

The UNIX timestamp is an integer value that represents the number of seconds elapsed since UNIX Epoch on January 1st, 1970 at 00:00:00 UTC. In short, it is a way to track the time as a running total of seconds. Hence, a UNIX timestamp is simply the number of seconds between a specific date and the UNIX Epoch.

Is UNIX timestamp in UTC?

Unix time is a way of representing a timestamp by representing the time as the number of seconds since January 1st, 1970 at 00:00:00 UTC. One of the primary benefits of using Unix time is that it can be represented as an integer making it easier to parse and use across different systems.


2 Answers

function timeConverter(UNIX_timestamp){    var a = new Date(UNIX_timestamp * 1000);    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];    var year = a.getFullYear();    var month = months[a.getMonth()];    var date = a.getDate();    var hour = a.getHours();    var min = a.getMinutes();    var sec = a.getSeconds();    var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;    return time;  }  console.log(timeConverter(0));
like image 35
shomrat Avatar answered Oct 07 '22 18:10

shomrat


let unix_timestamp = 1549312452  // Create a new JavaScript Date object based on the timestamp  // multiplied by 1000 so that the argument is in milliseconds, not seconds.  var date = new Date(unix_timestamp * 1000);  // Hours part from the timestamp  var hours = date.getHours();  // Minutes part from the timestamp  var minutes = "0" + date.getMinutes();  // Seconds part from the timestamp  var seconds = "0" + date.getSeconds();    // Will display time in 10:30:23 format  var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);    console.log(formattedTime);

For more information regarding the Date object, please refer to MDN or the ECMAScript 5 specification.

like image 114
Aron Rotteveel Avatar answered Oct 07 '22 18:10

Aron Rotteveel