Convert a Unix timestamp to Time using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 6, 2024
5 min

banner

# Table of Contents

  1. Convert a Unix timestamp to Time using JavaScript
  2. Convert a Timestamp to Relative Time (time ago) in JS

# Convert a Unix timestamp to Time using JavaScript

To convert a Unix timestamp to time:

  1. Use the Date() constructor to convert the Unix timestamp to a date.
  2. Use the toLocaleTimeString() method to render the time string according to your use case.
index.js
const unixTimestamp = 1664000732; const date = new Date(unixTimestamp * 1000); const enUS = date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit', }); console.log(enUS); // ๐Ÿ‘‰๏ธ 09:25:32โ€ฏAM const enGB = date.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit', second: '2-digit', }); console.log(enGB); // ๐Ÿ‘‰๏ธ 09:25:32 const deDE = date.toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit', second: '2-digit', }); console.log(deDE); // ๐Ÿ‘‰๏ธ ์˜ค์ „ 09:25:32

convert unix timestamp to time using javascript

The code for this article is available on GitHub

We used the Date() constructor to create a Date object from a Unix timestamp.

The Date() constructor takes a timestamp in milliseconds, so we had to multiply the Unix timestamp by 1000.

We used the toLocaleTimeString() method to get a string with a language-sensitive representation of the time portion of a date.

The method takes the locale and an options object as parameters.

You can remove the second property if you don't want to display the seconds in the result.

index.js
const unixTimestamp = 1664000732; const date = new Date(unixTimestamp * 1000); const enUS = date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', }); console.log(enUS); // ๐Ÿ‘‰๏ธ 09:25โ€ฏAM const enGB = date.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit', }); console.log(enGB); // ๐Ÿ‘‰๏ธ 09:25

remove second property to not display the seconds

We set the hour, minute and second properties to have them formatted as 2 digits even if the values are less than 10.

The other possible value for the properties is numeric.

If set to numeric, the time components will consist of 1 digit if their value is less than 10.

# Convert a Unix timestamp to Time using getHours, getMinutes and getSeconds

This is a three-step process:

  1. Create a Date object from the Unix timestamp.
  2. Use the getHours(), getMinutes() and getSeconds() methods to get the time components.
  3. Optionally, format the time as hh:mm:ss.
index.js
const unixTimestamp = 1664000732; const date = new Date(unixTimestamp * 1000); const hours = date.getHours(); const minutes = date.getMinutes(); const seconds = date.getSeconds(); // ๐Ÿ‘‡๏ธ Format as hh:mm:ss const time = `${padTo2Digits(hours)}:${padTo2Digits( minutes, )}:${padTo2Digits(seconds)}`; console.log(time); // ๐Ÿ‘‰๏ธ 09:25:32 function padTo2Digits(num) { return num.toString().padStart(2, '0'); }

convert unix timestamp to time using gethours getminutes getseconds

The code for this article is available on GitHub

We used the following 3 time-related methods to get the hours, minutes and seconds:

The last step is to format the time as hh:mm:ss.

The hours, minutes or seconds could contain a single digit (if their values are less than 10) or 2 digits.

To make the output consistently show 2 digits for each value, we have to add a leading zero if any of their values are less than 10.

The padTo2Digits function only adds a leading zero if the passed-in value has a length of less than 2.

index.js
function padTo2Digits(num) { return num.toString().padStart(2, '0'); } console.log(padTo2Digits(5)); // ๐Ÿ‘‰๏ธ '05' console.log(padTo2Digits(7)); // ๐Ÿ‘‰๏ธ '07' console.log(padTo2Digits(10)); // ๐Ÿ‘‰๏ธ '10'

In the scenario where the hours, minutes or seconds already have 2 digits, we leave the values as is.

If you need to render any of the date-related data, like the year, month or day of the month, you can use the following 3 methods:

  • Date.getFullYear() method - returns a four-digit number representing the year that corresponds to a date.

  • Date.getMonth() - returns an integer between 0 (January) and 11 (December) and represents the month for a given date. Yes, unfortunately, the getMonth method is off by 1.

  • Date.getDate() - returns an integer between 1 and 31 representing the day of the month for a specific date.

The getMonth method returns a zero-based month index from 0 to 11, meaning January is 0 and December is 11.

Here is a complete example that converts a Unix timestamp to a datetime string, formatted as YYYY-MM-DD hh:mm:ss.

index.js
const unixTimestamp = 1664000732; const date = new Date(unixTimestamp * 1000); const hours = date.getHours(); const minutes = date.getMinutes(); const seconds = date.getSeconds(); // ๐Ÿ‘‡๏ธ Format as hh:mm:ss const time = `${padTo2Digits(hours)}:${padTo2Digits(minutes)}:${padTo2Digits( seconds, )}`; const year = date.getFullYear(); const month = padTo2Digits(date.getMonth() + 1); const day = padTo2Digits(date.getDate()); const dateTime = `${year}-${month}-${day} ${time}`; console.log(dateTime); // ๐Ÿ‘‰๏ธ 2022-09-24 09:25:32 function padTo2Digits(num) { return num.toString().padStart(2, '0'); }

You can reorder the values, change the separators or make any other changes that suite your use case.

Note that we had to add 1 to the value the getMonth method returns because it returns a zero-based month (January = 0, February = 1, etc).

We padded the values for the month and day because they could be less than 10, and we want to output consistent results.

# Convert a Timestamp to Relative Time (time ago) in JS

To convert a timestamp to relative time:

  1. Create an object using the Intl.RelativeTimeFormat() constructor.
  2. Use the format() method on the constructor.
  3. The format method formats the value according to the provided options.
index.js
function relativeDays(timestamp) { const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto', }); const oneDayInMs = 1000 * 60 * 60 * 24; const daysDifference = Math.round( (timestamp - new Date().getTime()) / oneDayInMs, ); return rtf.format(daysDifference, 'day'); } // (Today is 13th Jan, 2023) // ๐Ÿ‘‡๏ธ 7 days ago console.log(relativeDays(new Date('2023-01-07').getTime())); // ๐Ÿ‘‡๏ธ 3 days ago console.log(relativeDays(new Date('2023-01-11').getTime())); // ๐Ÿ‘‡๏ธ 2 days ago console.log(relativeDays(new Date('2023-01-12').getTime())); // ๐Ÿ‘‡๏ธ today console.log(relativeDays(new Date().getTime())); // ๐Ÿ‘‡๏ธ in 91 days console.log(relativeDays(new Date('2023-04-15').getTime()));

convert timestamp to relative time

The code for this article is available on GitHub

The Intl.RelativeTimeFormat() constructor creates a Intl.RelativeTimeFormat object, on which we can call the format method.

The first parameter we passed to the Intl.RelativeTimeFormat() constructor is the locale.

The locale can be a string or array of BCP 27 language tag strings.

The second parameter is an options object.

The numeric property on the object has 2 possible values:

  • always (default) - e.g. 1 day ago.
  • auto - e.g. yesterday. The auto value allows us to not always have to use numeric values in the output and looks more natural in certain cases.

The format method takes 2 parameters:

  1. a value to use in the internationalized relative time message.
  2. the unit to use in the message. Possible values are: year, quarter, month, week, day, hour, minute and second.

In the example, we passed day as the unit to the format method.

For the first parameter, we calculated the difference in days between the passed-in timestamp and the current date.
index.js
function relativeDays(timestamp) { const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto', }); const oneDayInMs = 1000 * 60 * 60 * 24; const daysDifference = Math.round( (timestamp - new Date().getTime()) / oneDayInMs, ); return rtf.format(daysDifference, 'day'); }
The code for this article is available on GitHub

The getTime() method returns the number of milliseconds elapsed between the 1st of January, 1970 00:00:00 and the given date.

We subtracted the current timestamp from the passed-in timestamp and converted the result from milliseconds to days.

The result can be either a negative (timestamps in the past) or a positive (timestamps in the future) integer.

The function returns a string, formatted as: 2 days ago, in 5 days, yesterday, etc.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev