Home >Web Front-end >JS Tutorial >How to Extract the Time from a Unix Timestamp in JavaScript?

How to Extract the Time from a Unix Timestamp in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 15:59:17828browse

How to Extract the Time from a Unix Timestamp in JavaScript?

Extracting the Time from a Unix Timestamp in JavaScript

Unix timestamps, used to represent time values in MySQL databases, sometimes require extraction of just the time component for specific applications. To convert a Unix timestamp into time in JavaScript, follow these steps:

Step-by-Step Conversion

  1. Create a JavaScript Date Object:

    let unix_timestamp = 1549312452;
    let date = new Date(unix_timestamp * 1000); // Convert to milliseconds
  2. Extract Time Components:

    // Hours:
    const hours = date.getHours();
    
    // Minutes:
    const minutes = "0" + date.getMinutes(); // Pad zero if necessary
    
    // Seconds:
    const seconds = "0" + date.getSeconds(); // Pad zero if necessary
  3. Format the Time:

    const formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);

Example Code:

const unix_timestamp = 1549312452;

// Create a JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds
const date = new Date(unix_timestamp * 1000);

// Hours part from the timestamp
const hours = date.getHours();

// Minutes part from the timestamp
const minutes = "0" + date.getMinutes();

// Seconds part from the timestamp
const seconds = "0" + date.getSeconds();

// Will display time in 10:30:23 format
const formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);

console.log(formattedTime);

The above is the detailed content of How to Extract the Time from a Unix Timestamp in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn