重新定义日期javascript

问题描述

我国的官方日历是jalali! Jalali 是一种与公历有数学关系的日历。 我想更改 JS 中的 Date() 以返回 jalali 值。 有很多 lib 或 func 用于此,但我不想使用它们。 我可以重新定义 Date() 吗? 在哪里可以查看 Date() 源?

解决方法

您可以使用 toLocaleDateString();

let today = new Date().toLocaleDateString('fa-IR');
console.log(today);

fa-IR 适用于波斯语-伊朗,但可以找到所有 ISO 国家/地区代码 here

您也可以将选项设置为第二个参数,例如:

let options = { year: 'numeric',month: 'long',day: 'numeric' };
new Date().toLocaleDateString('fa-IR',options);
,

不要弄乱你不拥有的物品。您可以创建自己的日期对象,可能称为 jDate(在“jalali 日期”之后,我认为它与 Intl 对象的“波斯”日历相同)并在那里实现方法。

Intl.DateTimeFormat 构造函数返回一个对象,该对象具有一个 formatToParts 方法,您可以利用该方法来实现所需的 Date 方法,然后您可以处理标准 Date下面的对象,但从方法中返回 Jalali 值。例如以英语获取所有当前日期部分:

let f = new Intl.DateTimeFormat('en-GB-u-ca-persian',{
  year: 'numeric',day: 'numeric',weekday: 'long',hour: 'numeric',minute: 'numeric',second: 'numeric',hour12: false,});
console.log('Current Jalali date: ' + f.format(new Date()));

console.log('The parts:');  
f.formatToParts(new Date()).forEach(part => console.log(part.type + ': ' + part.value));

对于某些事情,您必须使用不同的选项多次运行 format 方法,例如获取月份名称和数字,因为这两者都由月份选项指定:month: 'long' 代表名称,month: 'numeric' 代表数字。