Temporal.PlainYearMonth.from()
Temporal.PlainYearMonth.from() 静态方法用于从另一个 Temporal.PlainYearMonth 对象、一个包含 year 和 month 属性的对象,或一个 RFC 9557 字符串创建一个新的 Temporal.PlainYearMonth 对象。
语法
Temporal.PlainYearMonth.from(info)
Temporal.PlainYearMonth.from(info, options)
参数
info-
以下之一:
Temporal.PlainYearMonth实例,它会创建一个该实例的副本。- 一个包含日期(可选)和日历的 RFC 9557 字符串。如果日历不是
iso8601,则必须提供日期。 - 一个包含以下属性的对象(按检索和验证的顺序)
calendar可选-
一个字符串,对应
calendarId属性。有关常用的日历类型列表,请参阅Intl.supportedValuesOf()。默认为"iso8601"。所有其他属性都将在此日历系统中解释(与Temporal.PlainYearMonth()构造函数不同,后者在 ISO 日历系统中解释这些值)。 era和eraYear-
一个字符串和一个整数,对应
era和eraYear属性。仅当日历系统有纪元(eras)时使用。era和eraYear必须同时提供。如果未提供,则必须提供year。如果同时提供了era、eraYear和year,它们必须一致。 月份-
对应
month属性。无论overflow选项如何,都必须为正数。 monthCode-
对应
monthCode属性。如果未提供,则必须提供month。如果同时提供了month和monthCode,它们必须一致。 年-
对应
year属性。
options可选-
包含以下属性的对象
overflow可选-
一个字符串,指定当日期组件超出范围时(使用对象
info时)的行为。可能的值有:"constrain"(默认)-
日期组件被限制在有效范围内。
"reject"-
如果日期组件超出范围,则抛出
RangeError。
返回值
一个 Temporal.PlainYearMonth 新对象,表示 info 中指定日历系统下的年份和月份。
每个 PlainYearMonth 内部存储一个完整的 ISO 8601 日期,该日期在目标日历系统中与暴露的值具有相同的年-月。当使用 toString() 字符串化时,会显示参考日期,输出为一个 ISO 日期。参考日期是任意选择但一致的;也就是说,每对 (year, month) 总是映射到相同的 ISO 参考日期。它不使用输入中提供的日期。相反,参考日期总是选择为该月份的第一个有效日期。
这种参考日期规范化确保了 equals() 可以直接比较底层 ISO 日期,而无需额外的计算。
异常
TypeError-
在以下情况之一中抛出
info不是对象或字符串。options不是对象或undefined。- 提供的属性不足以明确确定日期。通常需要提供
year(或era和eraYear)以及month(或monthCode)。
RangeError-
在以下情况之一中抛出
- 指定相同组件的提供的属性不一致。
- 提供的非数字属性无效;例如,如果
monthCode在此日历中从未是有效的月份代码。 - 提供的数字属性超出范围,并且
options.overflow设置为"reject"。 - 该信息不在 可表示范围 内,该范围是距 Unix 纪元 ±(108 + 1) 天,或大约 ±273,972.6 年。
示例
从对象创建 PlainYearMonth
// Year + month code
const ym = Temporal.PlainYearMonth.from({ year: 2021, monthCode: "M05" });
console.log(ym.toString()); // 2021-05
// Year + month
const ym2 = Temporal.PlainYearMonth.from({ year: 2021, month: 7 });
console.log(ym2.toString()); // 2021-07
// Year + month in a different calendar
const ym3 = Temporal.PlainYearMonth.from({
year: 5730,
month: 6,
calendar: "hebrew",
});
console.log(ym3.toString()); // 1970-02-07[u-ca=hebrew]
// Year + month code in a different calendar
const ym4 = Temporal.PlainYearMonth.from({
year: 5730,
monthCode: "M05L",
calendar: "hebrew",
});
console.log(ym4.toString()); // 1970-02-07[u-ca=hebrew]
控制溢出行为
默认情况下,超出范围的值会被裁剪到有效范围内。
const ym1 = Temporal.PlainYearMonth.from({ year: 2021, month: 13 });
console.log(ym1.toString()); // 2021-12
// 5732 is not a Hebrew leap year, so a different monthCode is chosen
const ym2 = Temporal.PlainYearMonth.from({
year: 5732,
monthCode: "M05L",
calendar: "hebrew",
});
console.log(ym2.toLocaleString("en-US", { calendar: "hebrew" })); // Adar 5732
const underlyingDate = Temporal.PlainDate.from(ym2.toString());
console.log(underlyingDate.year, underlyingDate.monthCode); // 5732 M06
你可以将此行为更改为抛出错误
Temporal.PlainYearMonth.from({ year: 2021, month: 13 }, { overflow: "reject" });
// RangeError: date value "month" not in 1..12: 13
规范
| 规范 |
|---|
| Temporal # sec-temporal.plainyearmonth.from |
浏览器兼容性
加载中…