How to Convert a Unix Timestamp to Time in JavaScript

The conversion of the UNIX Timestamp to time is required when the API request-response has the Unix format date-time value and requires to display it on the screen in a user-readable format. Let’s learn how you can convert a Unix timestamp to time with the help of JavaScript.

Since JavaScript works in milliseconds, you should convert the time into milliseconds by multiplying it by 1000. Then, the value is given to the Date() function to create a new date object.

Javascript date function
let unixTimestamp = 1579158622 //Since JavaScript works in milliseconds, you should convert // the time into milliseconds by multiplying it by 1000. let date = new Date(unixTimestamp * 1000); // Hours part from the timestamp let hours = date.getHours(); // Minutes part from the timestamp let minutes = "0" + date.getMinutes(); // Seconds part from the timestamp let seconds = "0" + date.getSeconds(); // Will display time in 11:10:22 format let formatTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2); console.log(formatTime);

A time value can be NaN as well, indicating that the Date object does not represent a particular instant of time.

The Date Object

There is a built-in Date object in JavaScript which handles all the date- and time-related operations. It is used for showing the current date/time, creating a calendar, build a timer, etc.. As the ECMAScript standard requires, the Date object should represent any date/time to millisecond precision, within 100 million days before/after 1/1/1970. JavaScript can represent the date/time until the year 275755.