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

如何将JSON返回的日期在HTML中转为日月年及仅年份两种展示格式

实现方案

用原生JS就能实现,不需要引入任何第三方库,以下是两种常用的实现方式:

方式1:用内置Date对象处理(推荐,代码最简洁)

const rawDate = data.release_date;
const dateObj = new Date(rawDate);

// 输出格式1:14 June 2021
const fullFormatDate = dateObj.toLocaleDateString('en-GB', {
  day: 'numeric',
  month: 'long',
  year: 'numeric'
});

// 输出格式2:仅年份
const yearOnly = dateObj.getFullYear();

// 按需插入DOM节点即可
document.getElementById('movie-date-full').innerHTML = fullFormatDate;
document.getElementById('movie-date-year').innerHTML = yearOnly;

说明:

  • 原生Date可以直接解析YYYY-MM-DD格式的日期字符串
  • toLocaleDateString配置中,month: 'long'会返回完整的英文月份名,指定en-GB locale会按「日 月 年」的顺序输出,完全匹配需求
  • 兼容性覆盖IE9及以上所有浏览器,满足绝大多数场景需求

方式2:手动拆分字符串处理(无兼容性问题,无时区坑)

如果需要避免Date对象可能带来的时区偏移问题,或者需要兼容极老的浏览器,可以直接拆分原始字符串处理:

const rawDate = data.release_date;
const [year, month, day] = rawDate.split('-');
const monthEnMap = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

// 输出格式1:14 June 2021
const fullFormatDate = `${Number(day)} ${monthEnMap[Number(month) - 1]} ${year}`;
// 输出格式2:仅年份
const yearOnly = year;

内容的提问来源于stack exchange,提问作者lowercase

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 19:15:07