JavaScript中不使用moment将毫秒转换为指定格式日期时间
Convert Milliseconds to Custom DateTime Format in Vanilla JavaScript (No Moment.js)
Got it, let's solve this without leaning on Moment.js—vanilla JavaScript has all the tools we need here. The goal is to turn a millisecond timestamp into the format DD-MM-YYYY HH:MM:SS (like 20-10-1994 06:00:00), so here's a straightforward approach:
Step-by-Step Function
We'll use the native Date object to extract each time component, format each part to ensure two-digit values, and finally stitch everything together:
function formatMsToDateTime(timestampMs) { // Create a Date object from the millisecond timestamp const date = new Date(timestampMs); // Extract each component, adjusting for 0-indexed months and adding leading zeros where needed const day = String(date.getDate()).padStart(2, '0'); const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-11, so +1 const year = date.getFullYear(); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); const seconds = String(date.getSeconds()).padStart(2, '0'); // Assemble into the target format return `${day}-${month}-${year} ${hours}:${minutes}:${seconds}`; } // Test with your example timestamp (782673600000 = 20 Oct 1994 06:00:00 UTC) console.log(formatMsToDateTime(782673600000)); // Output: "20-10-1994 06:00:00"
Note About Time Zones
The above code uses local time (based on the user's system clock/time zone). If you need UTC time instead, just swap out the get* methods with their getUTC* equivalents:
date.getDate()→date.getUTCDate()date.getMonth()→date.getUTCMonth()date.getHours()→date.getUTCHours()- And so on for minutes/seconds
This ensures the output reflects the UTC timestamp rather than local time.
内容的提问来源于stack exchange,提问作者Mahesh Chowdary
相关产品推荐
相关产品推荐

