Temporal.Instant.prototype.since()

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Phương thức since() của các instance Temporal.Instant trả về một đối tượng Temporal.Duration mới biểu diễn khoảng thời gian từ một instant khác (ở dạng có thể chuyển đổi bằng Temporal.Instant.from()) đến instant này. Duration là dương nếu instant kia nằm trước instant này, và âm nếu nằm sau.

Phương thức này thực hiện this - other. Để thực hiện other - this, hãy sử dụng phương thức until().

Cú pháp

js
since(other)
since(other, options)

Tham số

other

Một chuỗi hoặc instance Temporal.Instant biểu diễn một instant để trừ khỏi instant này. Nó được chuyển đổi thành đối tượng Temporal.Instant bằng cùng thuật toán như Temporal.Instant.from().

options Optional

Một đối tượng chứa các tùy chọn cho Temporal.Duration.prototype.round(), bao gồm largestUnit, roundingIncrement, roundingMode, và smallestUnit. largestUnitsmallestUnit chỉ chấp nhận các đơn vị: "hours", "minutes", "seconds", "milliseconds", "microseconds", "nanoseconds", hoặc dạng số ít của chúng. Đối với largestUnit, giá trị mặc định "auto" có nghĩa là "seconds" hoặc smallestUnit, tùy cái nào lớn hơn. Đối với smallestUnit, giá trị mặc định là "nanoseconds".

Giá trị trả về

Một đối tượng Temporal.Duration mới biểu diễn khoảng thời gian kể từ other đến instant này. Duration là dương nếu other nằm trước instant này, và âm nếu nằm sau.

Ngoại lệ

RangeError

Được ném ra nếu bất kỳ tùy chọn nào không hợp lệ.

Ví dụ

Sử dụng since()

js
const lastUpdated = Temporal.Instant.fromEpochMilliseconds(1735235418000);
const now = Temporal.Now.instant();
const duration = now.since(lastUpdated, { smallestUnit: "minute" });
console.log(`Last updated ${duration.toLocaleString("en-US")} ago`);

Cân bằng duration kết quả

Vì một instant không mang thông tin lịch, duration kết quả tránh các calendar duration, vốn mơ hồ khi không có lịch và tham chiếu thời gian. Do đó, kết quả không được cân bằnghours có thể lớn hơn 24. Để cân bằng duration, hãy làm tròn duration kết quả lại với largestUnit mong muốn, truyền relativeTo mang thông tin lịch.

js
const lastUpdated = Temporal.Instant.fromEpochMilliseconds(1735235418000);
const now = Temporal.Now.instant();
const duration = now.since(lastUpdated, { smallestUnit: "minutes" });
const roundedDuration = duration.round({
  largestUnit: "years",
  // Sử dụng lịch ISO; bạn có thể chuyển đổi sang lịch khác bằng
  // withCalendar()
  relativeTo: now.toZonedDateTimeISO("UTC"),
});
console.log(`Last updated ${roundedDuration.toLocaleString("en-US")} ago`);

Đặc tả

Specification
Temporal
# sec-temporal.instant.prototype.since

Tương thích trình duyệt

Xem thêm