Temporal.PlainYearMonth.prototype.toString()

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

toString() 方法是 Temporal.PlainYearMonth 例項的,它返回一個字串,該字串表示此年月(year-month)的 RFC 9557 格式

語法

js
toString()
toString(options)

引數

options 可選

包含以下屬性的物件

calendarName 可選

是否在返回值中顯示日曆註釋 ([u-ca=calendar_id])。可能的值是:

"auto"(預設值)

如果日曆不是 "iso8601",則包含日曆註解。如果日曆不是 "iso8601",則包含參考日。

"always"

始終包含日曆註解。參考日也始終包含。

"never"

從不包含日曆註解。這使得返回的字串無法恢復到相同的 Temporal.PlainYearMonth 例項,儘管年月值保持不變。如果日曆不是 "iso8601",則包含參考日。

"critical"

始終包含日曆註解,並新增一個關鍵標誌:[!u-ca=calendar_id]。在將字串傳送到某些系統時很有用,但對 Temporal 本身無用。參考日也始終包含。

返回值

一個 RFC 9557 格式 的字串,表示此年月。日曆註解按指定包含。如果包含日曆註解或日曆不是 "iso8601",則包含參考日。

異常

RangeError

如果任何選項無效,則丟擲。

TypeError

如果 options 不是物件或 undefined,則丟擲錯誤。

示例

使用 toString()

js
const ym = Temporal.PlainYearMonth.from({ year: 2021, month: 8 });
console.log(ym.toString()); // '2021-08'

const ym2 = Temporal.PlainYearMonth.from({
  year: 4658,
  monthCode: "M08",
  calendar: "chinese",
});
console.log(ym2.toString()); // '2021-09-07[u-ca=chinese]'

使用選項

js
const isoYM = Temporal.PlainYearMonth.from({ year: 2021, month: 8 });
const ym = Temporal.PlainYearMonth.from({
  year: 4658,
  monthCode: "M08",
  calendar: "chinese",
});
console.log(isoYM.toString({ calendarName: "auto" })); // '2021-08'
console.log(ym.toString({ calendarName: "auto" })); // '2021-09-07[u-ca=chinese]'
console.log(isoYM.toString({ calendarName: "always" })); // '2021-08-01[u-ca=iso8601]'
console.log(ym.toString({ calendarName: "always" })); // '2021-09-07[u-ca=chinese]'
console.log(isoYM.toString({ calendarName: "never" })); // '2021-08'
console.log(ym.toString({ calendarName: "never" })); // '2021-09-07'
console.log(isoYM.toString({ calendarName: "critical" })); // '2021-08-01[!u-ca=iso8601]'
console.log(ym.toString({ calendarName: "critical" })); // '2021-09-07[!u-ca=chinese]'

規範

規範
Temporal
# sec-temporal.plainyearmonth.prototype.tostring

瀏覽器相容性

另見