PASSWORD RESET

Your destination for complete Tech news

How to convert a Unix timestamp to time in JavaScript?

447 0
< 1 min read

To convert a Unix timestamp to a human-readable time in JavaScript, you can use the Date object and pass the timestamp as an argument to the constructor. The Date object provides a number of methods for manipulating and formatting dates and times.

Here’s an example of how you can convert a Unix timestamp to a string representing the time in a specific format:

let timestamp = 1618583600000; // Unix timestamp in milliseconds
let date = new Date(timestamp);
let formattedTime = date.toLocaleTimeString();
console.log(formattedTime); // "11:00:00 AM"

In this example, the toLocaleTimeString() method is used to convert the Date object to a string representation of the time in the user’s local time zone, using the default formatting for that locale.

You can also use the toUTCString() method to convert the Date object to a string representation of the time in UTC (Coordinated Universal Time).

let timestamp = 1618583600000; // Unix timestamp in milliseconds
let date = new Date(timestamp);
let formattedTime = date.toUTCString();
console.log(formattedTime); // "Fri, 05 Nov 2021 10:00:00 GMT"

If you want to customize the formatting of the time string, you can use the toLocaleDateString() and toLocaleTimeString() methods in combination with the Intl.DateTimeFormat object, which allows you to specify the format of the date and time using a pattern string. Here’s an example:

let timestamp = 1618583600000; // Unix timestamp in milliseconds
let date = new Date(timestamp);
let formattedTime = new Intl.DateTimeFormat('en-US', {
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  hour12: true
}).format(date);
console.log(formattedTime); // "11:00:00 AM"

There are many other methods and options available for formatting dates and times in JavaScript. You can refer to the documentation for the Date object and the Intl.DateTimeFormat object for more information.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.