instant.valueOf
could return epochNanoseconds
instead of throwing #3080
Description
If I follow the discussion in #1681 #517 correctly, along with the explained rationale, instant.valueOf
was made to throw an error because the relational operators <
, <=
, >
, or >=
would not work correctly if the instant is implicitly coerced to a string. However, if you instead have instant.valueOf
return the epochNanoseconds
as a bigint, these operators would work just fine. So can we do that? This would also fix the use case I previously described in #1840.
Here’s a simple patch:
Temporal.Instant.prototype.valueOf = function() {
return this.epochNanoseconds;
};
And two test cases:
const i1 = Temporal.PlainDate.from("2020-01-04").toZonedDateTime({timeZone: "America/Los_Angeles"}).toInstant();
const i2 = Temporal.PlainDate.from("2020-01-08").toZonedDateTime({timeZone: "America/Los_Angeles"}).toInstant();
i1 < i2; // true
const i3 = Temporal.PlainDate.from("-002020-01-04").toZonedDateTime({timeZone: "America/Los_Angeles"}).toInstant();
const i4 = Temporal.PlainDate.from("-002222-01-04").toZonedDateTime({timeZone: "America/Los_Angeles"}).toInstant();
i3 < i4; // false since 2020 BCE is after 2222 BCE
Furthermore, since the Temporal.Instant
construct accepts a bigint, it makes sense that valueOf
would return the same.
I see now this was previously suggested in js-temporal/proposal-temporal-v2#6 (comment); is it too late to change? (And I guess this argument applies to Temporal.ZonedDateTime
, too.)