Temporal.ZonedDateTime.prototype.round()
Temporal.ZonedDateTime 例項的 round() 方法返回一個新的 Temporal.ZonedDateTime 物件,表示此日期-時間按照給定單位進行四捨五入後的結果。
語法
round(smallestUnit)
round(options)
引數
smallestUnit(最小單位)-
表示
smallestUnit選項的字串。這是一個便捷的過載,因此round(smallestUnit)等價於round({ smallestUnit }),其中smallestUnit是一個字串。 options-
一個包含以下部分或全部屬性的物件(按檢索和驗證的順序):
roundingIncrement可選-
一個數字(截斷為整數),表示給定
smallestUnit中的舍入增量。預設為1。對於"day"以外的所有smallestUnit值,增量必須是該單位最大值的約數;例如,如果單位是小時,增量必須是 24 的約數,並且不能是 24 本身,這意味著它可以是 1、2、3、4、6、8 或 12。對於"day",增量必須是 1。 roundingMode可選-
一個字串,指定如何對
smallestUnit的小數部分進行四捨五入。參見Intl.NumberFormat()。預設為"halfExpand"。 smallestUnit(最小單位)-
一個字串,表示輸出中包含的最小單位。該值必須是以下之一:
"day"、"hour"、"minute"、"second"、"millisecond"、"microsecond"、"nanosecond",或它們的複數形式。對於大於"nanosecond"的單位,smallestUnit的小數部分將根據roundingIncrement和roundingMode設定進行四捨五入。
返回值
一個新的 Temporal.ZonedDateTime 物件,表示此日期-時間按照給定單位四捨五入後的結果,其中所有小於 smallestUnit 的單位都歸零。
如果 smallestUnit 是 "day",則返回的日期-時間將是此日期或次日的一天開始,具體取決於 roundingMode 以及與這兩個時刻的距離。否則,舍入首先在其 PlainDateTime 上執行(與 Temporal.PlainDateTime.prototype.round() 相同),然後以相同的時區重新解釋,使用 disambiguation: "compatible", offset: "prefer"。參見從本地時間到 UTC 時間的模糊性和間隔以及偏移量模糊性。
異常
RangeError-
如果任何選項無效,則丟擲。
示例
小單位的四捨五入
const zdt = Temporal.ZonedDateTime.from(
"2021-07-01T12:34:56.123456789[America/New_York]",
);
const nearestMillisecond = zdt.round("millisecond");
console.log(nearestMillisecond.toString()); // 2021-07-01T12:34:56.123-04:00[America/New_York]
const nearestHalfHour = zdt.round({
smallestUnit: "minute",
roundingIncrement: 30,
});
console.log(nearestHalfHour.toString()); // 2021-07-01T12:30:00-04:00[America/New_York]
const nextDay = zdt.round({ smallestUnit: "day", roundingMode: "ceil" });
console.log(nextDay.toString()); // 2021-07-02T00:00:00-04:00[America/New_York]
四捨五入後的模糊性
四捨五入後的日期-時間在給定 timezone 中可能存在模糊性。模糊性總是使用 disambiguation: "compatible", offset: "prefer" 來解決。這是一個快速示例:
const zdt = Temporal.ZonedDateTime.from(
"2024-03-10T01:00:00-05:00[America/New_York]",
);
const rounded = zdt.round({ smallestUnit: "hour", roundingIncrement: 2 });
// The result is supposed to be 2024-03-10T02:00:00-05:00[America/New_York],
// but this time does not exist. `disambiguation: "compatible"` tells us to move
// forward by 1 hour.
console.log(rounded.toString()); // 2024-03-10T03:00:00-04:00[America/New_York]
規範
| 規範 |
|---|
| Temporal # sec-temporal.zoneddatetime.prototype.round |
瀏覽器相容性
載入中…