怎么把后端返回的字符串日期转成前端能用的时间格式?

Prog.泽睿 阅读 20

我从接口拿到的日期是字符串 “2024-03-15 14:30:00″,想在页面上显示成“2024年3月15日 14:30”,但直接 new Date() 解析出来是 Invalid Date,试了 JSON.parse 也不行,到底该怎么转换啊?

我的 HTML 是这样用的:

<div id="time"></div>
<script>
  const rawDate = "2024-03-15 14:30:00";
  const showTime = new Date(rawDate).toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  });
  document.getElementById('time').innerText = showTime;
</script>
我来解答 赞 6 收藏
二维码
手机扫码查看
1 条解答
乐萱
乐萱 Lv1
这问题我太熟了,后端返回的字符串 "2024-03-15 14:30:00" 格式在浏览器里确实会被 new Date() 拒绝解析,因为不同浏览器对这种非 ISO 标准格式支持不一致,有的直接返回 Invalid Date。

最稳妥的方案是手动拆解字符串,别依赖 new Date() 去猜。比如:

const rawDate = "2024-03-15 14:30:00";
const [datePart, timePart] = rawDate.split(" ");
const [year, month, day] = datePart.split("-").map(Number);
const [hour, minute] = timePart.split(":").map(Number);
const dateObj = new Date(year, month - 1, day, hour, minute);

const showTime = dateObj.toLocaleString('zh-CN', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
document.getElementById("time").innerText = showTime;


注意 month - 1,因为 JS 的 Date 月份是从 0 开始的。这样写效率更高,也不依赖浏览器兼容性,而且能精确控制输出格式。最后输出是 2024/3/15 14:30,如果你要加“年”“日”这些汉字,可以再拼一下,或者用 toLocaleDateString 分开处理:

const showTime = ${dateObj.getFullYear()}年${dateObj.getMonth() + 1}月${dateObj.getDate()}日 ${String(dateObj.getHours()).padStart(2, "0")}:${String(dateObj.getMinutes()).padStart(2, "0")};


这样直接输出 2024年3月15日 14:30,省得再处理 locale 的坑。
点赞 3
2026-02-26 14:11