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:
Create a JavaScript Date Object:
let unix_timestamp = 1549312452; let date = new Date(unix_timestamp * 1000); // Convert to milliseconds
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
Format the Time:
const formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
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!