Temporal.ZonedDateTime.prototype.withPlainTime()

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

Temporal.ZonedDateTime 实例的 withPlainTime() 方法返回一个新的 Temporal.ZonedDateTime 对象,表示此日期-时间,其中时间部分完全替换为新的时间(形式可由 Temporal.PlainTime.from() 转换)。

此方法将替换所有时间属性,未指定的属性默认为 0。如果只想替换部分时间属性,请改用 with() 方法。

语法

js
withPlainTime()
withPlainTime(plainTime)

参数

plainTime 可选

一个字符串、一个对象或一个 Temporal.PlainTime 实例,表示新的时间。它使用与 Temporal.PlainTime.from() 相同的算法转换为 Temporal.PlainTime 对象。如果未指定,时间部分将设置为一天开始(通常是 00:00:00,除非由于偏移量转换而不存在)。消歧总是以 "compatible" 模式发生;如果想使用不同的模式,请改用 with() 方法。

返回值

一个新的 Temporal.ZonedDateTime 对象,其中日期部分和时区从原始日期-时间复制,时间部分替换为新的时间。

示例

使用 withPlainTime()

js
const zdt = Temporal.ZonedDateTime.from(
  "2021-07-01T12:34:56[America/New_York]",
);

// You can pass a string
const newZDT = zdt.withPlainTime("13:45:00");
console.log(newZDT.toString()); // "2021-07-01T13:45:00-04:00[America/New_York]"

// You can only specify some time properties, and the rest default to 0;
// for the with() method, they would be copied from the original date-time
const newZDT2 = zdt.withPlainTime({ hour: 13 });
console.log(newZDT2.toString()); // "2021-07-01T13:00:00-04:00[America/New_York]"

// You can pass nothing to set the time to midnight
const newZDT3 = zdt.withPlainTime();
console.log(newZDT3.toString()); // "2021-07-01T00:00:00-04:00[America/New_York]"

// But, if midnight doesn't exist, it may be a different time
const zdt2 = Temporal.ZonedDateTime.from(
  "2015-10-18T12:00-02:00[America/Sao_Paulo]",
);
console.log(zdt2.withPlainTime().toString()); // "2015-10-18T01:00:00-02:00[America/Sao_Paulo]"

规范

规范
Temporal
# sec-temporal.zoneddatetime.prototype.withplaintime

浏览器兼容性

另见