Convert a Unix timestamp to time in JavaScript

featured Image

This short out how to convert a Unix timestamp to a time format using JavaScript.

The UNIX time (also known as Epoch time or UNIX Epoch time) is a single signed number that increases every second. The timestamp of UNIX time is the total number of seconds that’s been calculated since January 1, 1970 (midnight UTC/GMT).

The timestamp makes it easier for the computer to manipulate or store than the conventional date-time formats.

So to convert a UNIX timestamp to a time format in JavaScript, we can follow these steps:

  1. Convert Unix timestamp from seconds to milliseconds by multiplying it by 1000.
  2. Create a new date object using the new Date() constructor method.
  3. Use toLocaleTimeString() method to extract the time.

Convert Unix timestamp to time using toLocaleTimeString()

let unix_timestamp = 1549312452
var date = new Date(unix_timestamp * 1000);

console.log(date.toLocaleTimeString())

Output:

8:34:12 PM

Code Explanation:

unix_timestamp 1000* : So that the argument is in milliseconds instead of seconds

date.toLocaleTimeString() : It returns us the time portion of the date as a string using locale conventions.

If you want to remove the seconds ( like this, 8:34 PM ) from to toLocaleTimeString() method, you can code like this.

console.log(date.toLocaleTimeString([], {timeStyle: 'short'}))

// Output : 8:34 PM

The timeStyle is the time formatting style that can be used as an optional argument. It gives us 4 options: full, long, medium, short.

Resources:

Date.prototype.toLocaleTimeString()

timeStyle property

Related Topics:

Get Current Date In Different Date Formats In JavaScript

Convert Date To Long Date Format Using Javascript

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more