Convert a Unix timestamp to time in JavaScript
Find out how to convert a unix timestamp to time format in JavaScript using toLocaleTimeString() method.
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:
- Convert Unix timestamp from seconds to milliseconds by multiplying it by 1000.
- Create a new date object using the
new Date()constructor method. - 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()
Related Topics:
Related Posts
Convert seconds to minutes and seconds (mm:ss) using JavaScript
Find out how to convert seconds to minutes and second format mm:ss using toString() and padStart() in JavaScript.
JavaScript - Convert Days to Seconds
Tutorial to write a program to convert days to seconds using JavaScript.
Fix error:0308010C:digital envelope routines::unsupported
Learn to solve the "Error: error:0308010C:digital envelope routines::unsupported" error in Node.js application (Vue, Angular or react) using the solutions in this article.
Press Shift + Enter for new Line in Textarea
Override default textarea behavior on Enter key press without Shift, prevent new lines, and take custom actions like submitting forms instead. Still allow Shift+Enter newlines.
