🧐 Use Case
When working with data that uses Unix timestamps (like logs, APIs, or databases), it's essential to display them in a human-readable format (YYYY-MM-DD HH:mm:ss). JavaScript provides built-in methods to handle this, but careful handling of timezones, padding for single-digit numbers, and date formatting is needed.
💡 Solution Steps
1️⃣ Parse the Unix timestamp: Convert the numeric Unix timestamp to a Date
object.
2️⃣ Extract date components: Use JavaScript's Date
methods to extract the year, month, day, hour, minute, and second in UTC.
3️⃣ Pad single-digit numbers: Ensure numbers like 9 become "09" for consistent formatting.
4️⃣ Assemble the formatted string: Concatenate all components into a standard format YYYY-MM-DD HH:mm:ss
.
📜 JavaScript Code: UnixToStandardTime.js
function UnixToStandard(TS) {
TS = Number(TS);
var date = new Date(TS);
// Helper to pad with leading zeros
function pad(n) {
return n.toString().padStart(2, '0');
}
var Y = date.getUTCFullYear();
var M = pad(date.getUTCMonth() + 1); // Months are zero-based
var D = pad(date.getUTCDate());
var H = pad(date.getUTCHours());
var m = pad(date.getUTCMinutes());
var s = pad(date.getUTCSeconds());
var result = Y + "-" + M + "-" + D + " " + H + ":" + m + ":" + s;
return result;
}
🚀 Usage Example
let timestamp = 1696177311000; // Example Unix timestamp
console.log(UnixToStandard(timestamp)); // Output: e.g., "2023-10-01 17:15:11"
This approach ensures reliable and standardized UTC time conversion, making it easier to display and interpret timestamps across different systems!
Screenshots:
Test:
No comments:
Post a Comment