How to Convert a Unix Timestamp to Time in Javascript

Avatar

By squashlabs, Last Updated: Dec. 7, 2023

How to Convert a Unix Timestamp to Time in Javascript

To convert a Unix timestamp to time in Javascript, you can use the built-in Date object and its methods. Here are two possible ways to achieve this:

Using the toLocaleString() method

The toLocaleString() method of the Date object returns a string representation of the date and time based on the host system's current locale settings. By passing the Unix timestamp multiplied by 1000 (to convert it to milliseconds) as an argument to the Date constructor, you can create a Date object representing that timestamp. You can then use the toLocaleString() method to obtain the formatted date and time string.

const unixTimestamp = 1622771526;
const date = new Date(unixTimestamp * 1000);
const timeString = date.toLocaleString();

console.log(timeString);

This will output the date and time string in the format determined by the host system's locale settings, such as "6/4/2021, 1:52:06 PM" in the US.

Related Article: Integrating React Components with Vanilla JavaScript

Using the toLocaleTimeString() method

If you only need the time portion of the Unix timestamp, you can use the toLocaleTimeString() method instead. This method returns a string representing the time portion of the Date object based on the host system's current locale settings.

const unixTimestamp = 1622771526;
const date = new Date(unixTimestamp * 1000);
const timeString = date.toLocaleTimeString();

console.log(timeString);

This will output the time string in the format determined by the host system's locale settings, such as "1:52:06 PM" in the US.

Alternative Approach: Using the Intl.DateTimeFormat object

Another alternative to convert a Unix timestamp to time in Javascript is by using the Intl.DateTimeFormat object. This object provides a way to format dates and times based on the specified locale.

const unixTimestamp = 1622771526;
const date = new Date(unixTimestamp * 1000);
const timeFormatter = new Intl.DateTimeFormat(undefined, { timeStyle: 'medium' });
const timeString = timeFormatter.format(date);

console.log(timeString);

The Intl.DateTimeFormat object is initialized with the desired locale (in this case, undefined to use the default locale) and an options object specifying the desired time style ('medium' in this example). The format() method is then used to obtain the formatted time string.

This approach gives you more control over the formatting options, allowing you to customize the output based on your specific requirements.

Best Practices

When converting a Unix timestamp to time in Javascript, keep the following best practices in mind:

1. Ensure that the Unix timestamp is in seconds and not milliseconds. If you have a Unix timestamp in milliseconds, divide it by 1000 to convert it to seconds before performing the conversion.

2. If you need to perform multiple conversions or formatting operations, consider creating a helper function to encapsulate the logic. This can improve code readability and reusability.

3. Be aware of the limitations of date and time formatting in different locales. Different locales may have different conventions for date and time representation, including the order of components, separators, and formatting styles. Test your code with different locales to ensure it works as expected.

4. When dealing with time zones, be mindful of the fact that Unix timestamps represent a point in time relative to Coordinated Universal Time (UTC). If you need to display the time in a specific time zone, you may need to adjust the date object accordingly.

You May Also Like

How to Check a Radio Button Using jQuery

Simple instructions on how to check a radio button using jQuery in JavaScript. Learn how to use the prop() and attr() methods effectively. Discover b… read more

How to Work with Async Calls in JavaScript

Asynchronous calls are a fundamental aspect of JavaScript programming, but they can also be challenging to work with. This article serves as a detail… read more

Implementing i18n and l10n in Your Node.js Apps

Internationalization (i18n) and localization (l10n) are crucial aspects of developing Node.js apps. This article explores the process of implementing… read more

How to Integrate UseHistory from the React Router DOM

A simple guide for using UseHistory from React Router Dom in JavaScript. Learn how to import the useHistory hook, access the history object, navigate… read more

Integrating HTMX with Javascript Frameworks

Integrating HTMX with JavaScript frameworks is a valuable skill for frontend developers. This article provides best practices for using HTMX with pop… read more

Advanced Node.js: Event Loop, Async, Buffer, Stream & More

Node.js is a powerful platform for building scalable and web applications. In this article, we will explore advanced features of Node.js such as the … read more

Invoking Angular Component Functions via JavaScript

Learn how to call Angular component functions using JavaScript. Discover the syntax and different ways to invoke these functions, as well as how to t… read more

How to Check and Update npm Packages in JavaScript

In this guide, you will learn how to use npm to check and update packages in JavaScript projects. You will explore the process of checking for outdat… read more

How to Access Cookies Using Javascript

Accessing cookies using JavaScript is a practical guide that provides step-by-step instructions on how to manipulate cookies in JavaScript. From acce… read more

How to Access the Last Item in a JavaScript Array

Accessing the last item in a JavaScript array can be done using different methods. One approach is to use the index position, while another option is… read more