Q:

How to Convert a Unix Timestamp to Time in JavaScript

0

How to Convert a Unix Timestamp to Time in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the new Date() Syntax

Simply multiply Unix timestamp by 1000 to convert it to a JavaScript time, because Unix timestamp measures time as a number of seconds, whereas in JavaScript time is fundamentally specified as the number of milliseconds (elapsed since January 1, 1970 at 00:00:00 UTC).

The following example demonstrates how to convert Unix timestamp to JavaScript time and extract date and time part from it. Let's try it out and see how it works:

// Timestamp in seconds
var unixTimestamp = 1651822834;

/* Create a new JavaScript Date object based on Unix timestamp.
Multiplied it by 1000 to convert it into milliseconds */
var date = new Date(unixTimestamp * 1000);

// Generate date string
console.log(date.toLocaleDateString("en-US"));   // Prints: 5/6/2022
console.log(date.toLocaleDateString("en-GB"));   // Prints: 06/05/2022
console.log(date.toLocaleDateString("default")); // Prints: 5/6/2022

// Generate time string
console.log(date.toLocaleTimeString("en-US"));   // Prints: 1:10:34 PM
console.log(date.toLocaleTimeString("it-IT"));   // Prints: 13:10:34
console.log(date.toLocaleTimeString("default")); // Prints: 1:10:34 PM

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Copy Array by Value in JavaScript... >>
<< How to Compare Two Dates in JavaScript...