intl.datetimeformat 不能直接取年份字符串,因为它只控制格式化输出是否显示年份,不提供提取功能;需调用 format(new date()) 并配置 year: 'numeric' 才能获得如 "2024" 的字符串。

Intl.DateTimeFormat 为什么不能直接取年份字符串
很多人看到 Intl.DateTimeFormat 的 year 选项就以为能像 new Date().getFullYear() 那样直接拿到数字年份,其实不是——它只控制格式化输出时是否显示年份,不提供提取功能。调用 format() 返回的是带格式的字符串(比如 "2024" 或 "24"),但你得自己传入一个日期对象才能触发格式化。
正确做法:用 format(new Date()) 提取完整年份
要得到四位数年份(如版权常用的 "2024"),必须显式传入当前日期,并确保 year: 'numeric' 且其他字段设为 undefined 或空字符串,避免多余内容干扰:
const year = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: undefined,
day: undefined,
hour: undefined,
minute: undefined,
second: undefined
}).format(new Date());
更简洁安全的写法是只保留必要选项:
const year = new Intl.DateTimeFormat('en-US', { year: 'numeric' }).format(new Date());
-
year: 'numeric'是关键,'2-digit'会返回"24",不适合版权 - 不指定
month/day等,浏览器默认不渲染它们,但显式设为undefined更可靠(尤其在旧版 Safari 中) - 区域设置(如
'en-US')影响年份分隔符和排序,但对纯年份输出基本无影响;用undefined会回退到运行环境默认,可能不稳定
常见错误:用 resolvedOptions() 误以为能取值
有人尝试调用 resolvedOptions().year,结果得到 'numeric' 这个字符串,而不是实际年份——这是配置项名,不是运行时值。这个方法只返回你传进去的选项解析结果,和当前时间完全无关。
- ❌ 错误:
new Intl.DateTimeFormat().resolvedOptions().year→ 返回"numeric" - ✅ 正确:
new Intl.DateTimeFormat().format(new Date())→ 返回"2024" - 注意:如果没传
new Date(),format()默认用当前时间,但显式传入更清晰、可测试
嵌入 HTML 版权栏的实用写法
直接在脚本里更新 DOM 元素最稳妥,避免服务端渲染或构建时静态写死:
document.getElementById('copyright-year').textContent =
new Intl.DateTimeFormat('en-US', { year: 'numeric' }).format(new Date());
对应 HTML:
<footer>© <span id="copyright-year"></span> Your Company</footer>
- 别用
innerHTML拼接,防止 XSS;纯文本用textContent - 如果页面有多个版权位置,建议封装成函数并缓存结果,避免重复调用
new Date()(虽然影响极小) - SSR 场景下需注意:服务端执行时得到的是服务器时间,和客户端不一致;前端 hydrate 后应重新运行一次
resolvedOptions 和 format 是高频翻车点。










