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

如何在JavaScript中仅获取本地化年份?

获取本地化历法年份的实现方法

你可以直接通过toLocaleDateString的配置参数来单独提取本地化年份,不需要专门的toLocaleYear()方法。关键是在第二个参数里指定只返回年份,并按需设置对应的历法类型。

具体实现示例

以下是针对不同语言/历法的代码示例:

  • 英文(公历):
const enYear = new Date().toLocaleDateString('en', { year: 'numeric' });
console.log(enYear); // 输出当前公历年份,如 2023
  • 阿拉伯语(伊斯兰历):
const arYear = new Date().toLocaleDateString('ar', { 
  year: 'numeric',
  calendar: 'islamic'
});
console.log(arYear); // 输出对应伊斯兰历年份,如 1444
  • 波斯语(波斯历):
const faYear = new Date().toLocaleDateString('fa', { 
  year: 'numeric',
  calendar: 'persian'
});
console.log(faYear); // 输出对应波斯历年份,如 1401

参数说明

  • year: 'numeric':明确告知API只返回年份的数值形式
  • calendar:可选参数,用于指定历法类型,常见取值包括'gregory'(公历,默认)、'islamic'(伊斯兰历)、'persian'(波斯历)等,主流现代浏览器均支持这些常见历法的解析。

如果需要适配更多地区的历法,只需替换对应的语言标识和calendar参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:23:10