Last updated: Mar 6, 2024
Reading timeยท5 min
To convert a Unix timestamp to time:
Date()
constructor to convert the Unix timestamp to a date.toLocaleTimeString()
method to render the time string according to
your use case.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
We used the Date() constructor
to create a Date
object from a Unix timestamp.
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.
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
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
.
This is a three-step process:
Date
object from the Unix timestamp.getHours()
, getMinutes()
and getSeconds()
methods to get the
time components.hh:mm:ss
.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'); }
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.
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
.
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.
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
.
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.
To convert a timestamp to relative time:
Intl.RelativeTimeFormat()
constructor.format()
method on the constructor.format
method formats the value according to the provided options.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()));
The
Intl.RelativeTimeFormat()
constructor creates a Intl.RelativeTimeFormat
object, on which we can call the
format
method.
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:
value
to use in the internationalized relative time message.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.
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 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 function returns a string, formatted as: 2 days ago
, in 5 days
,
yesterday
, etc.
You can learn more about the related topics by checking out the following tutorials: