You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:38:27