Open In App

How to convert Unix timestamp to time in JavaScript ?

In this article, we will see how to convert UNIX timestamps to time.

These are the following approaches:



Method 1: Using the toUTCString() method

Syntax: 

dateObj = new Date(unixTimestamp * 1000);
utcString = dateObj.toUTCString();
time = utcString.slice(-11, -4);

Example: This example shows the conversion of time.






function convertTimestamptoTime() {
 
    let unixTimestamp = 10637282;
 
    // Convert to milliseconds and
    // then create a new Date object
    let dateObj = new Date(unixTimestamp * 1000);
    let utcString = dateObj.toUTCString();
 
    let time = utcString.slice(-11, -4);
 
    console.log(time);
}
 
convertTimestamptoTime();

Output
2:48:02

Method 2: Getting individual hours, minutes, and seconds

Syntax: 

dateObj = new Date(unixTimestamp * 1000);

// Get hours from the timestamp
hours = dateObj.getUTCHours();

// Get minutes part from the timestamp
minutes = dateObj.getUTCMinutes();

// Get seconds part from the timestamp
seconds = dateObj.getUTCSeconds();

formattedTime = hours.toString()
.padStart(2, '0') + ':'
+ minutes.toString()
.padStart(2, '0') + ':'
+ seconds.toString()
.padStart(2, '0');

Example: This example shows the conversion of time.




function convertTimestamptoTime() {
 
    let unixTimestamp = 10637282;
 
    // Convert to milliseconds and
    // then create a new Date object
    let dateObj = new Date(unixTimestamp * 1000);
 
    // Get hours from the timestamp
    let hours = dateObj.getUTCHours();
 
    // Get minutes part from the timestamp
    let minutes = dateObj.getUTCMinutes();
 
    // Get seconds part from the timestamp
    let seconds = dateObj.getUTCSeconds();
 
    let formattedTime = hours.toString().padStart(2, '0')
        + ':' + minutes.toString().padStart(2, '0')
        + ':' + seconds.toString().padStart(2, '0');
 
    console.log(formattedTime);
}
 
convertTimestamptoTime();

Output
02:48:02

Article Tags :