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
since(other)
since(other, options)
Tham số
other-
Một chuỗi hoặc instance
Temporal.Instantbiểu diễn một instant để trừ khỏi instant này. Nó được chuyển đổi thành đối tượngTemporal.Instantbằng cùng thuật toán nhưTemporal.Instant.from(). optionsOptional-
Một đối tượng chứa các tùy chọn cho
Temporal.Duration.prototype.round(), bao gồmlargestUnit,roundingIncrement,roundingMode, vàsmallestUnit.largestUnitvàsmallestUnitchỉ 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ớilargestUnit, giá trị mặc định"auto"có nghĩa là"seconds"hoặcsmallestUnit, tùy cái nào lớn hơn. Đối vớismallestUnit, 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()
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ằng vì hours 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.
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> |