LibJS: Implement Temporal.ZonedDateTime.prototype.epochSeconds

This commit is contained in:
Linus Groh 2021-08-04 23:01:24 +01:00 committed by Andreas Kling
parent a1082412ef
commit 47135af987
Notes: sideshowbarker 2024-07-18 07:27:41 +09:00
3 changed files with 36 additions and 0 deletions

View File

@ -42,6 +42,7 @@ void ZonedDateTimePrototype::initialize(GlobalObject& global_object)
define_native_accessor(vm.names.millisecond, millisecond_getter, {}, Attribute::Configurable);
define_native_accessor(vm.names.microsecond, microsecond_getter, {}, Attribute::Configurable);
define_native_accessor(vm.names.nanosecond, nanosecond_getter, {}, Attribute::Configurable);
define_native_accessor(vm.names.epochSeconds, epoch_seconds_getter, {}, Attribute::Configurable);
}
static ZonedDateTime* typed_this(GlobalObject& global_object)
@ -353,4 +354,23 @@ JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::nanosecond_getter)
return Value(temporal_date_time->iso_nanosecond());
}
// 6.3.15 get Temporal.ZonedDateTime.prototype.epochSeconds, https://tc39.es/proposal-temporal/#sec-get-temporal.zoneddatetime.prototype.epochseconds
JS_DEFINE_NATIVE_FUNCTION(ZonedDateTimePrototype::epoch_seconds_getter)
{
// 1. Let zonedDateTime be the this value.
// 2. Perform ? RequireInternalSlot(zonedDateTime, [[InitializedTemporalZonedDateTime]]).
auto* zoned_date_time = typed_this(global_object);
if (vm.exception())
return {};
// 3. Let ns be zonedDateTime.[[Nanoseconds]].
auto& ns = zoned_date_time->nanoseconds();
// 4. Let s be RoundTowardsZero((ns) / 10^9).
auto s = ns.big_integer().divided_by(Crypto::UnsignedBigInteger { 1'000'000'000 }).quotient;
// 5. Return 𝔽(s).
return Value((double)s.to_base(10).to_int<i64>().value());
}
}

View File

@ -31,6 +31,7 @@ private:
JS_DECLARE_NATIVE_FUNCTION(millisecond_getter);
JS_DECLARE_NATIVE_FUNCTION(microsecond_getter);
JS_DECLARE_NATIVE_FUNCTION(nanosecond_getter);
JS_DECLARE_NATIVE_FUNCTION(epoch_seconds_getter);
};
}

View File

@ -0,0 +1,15 @@
describe("correct behavior", () => {
test("basic functionality", () => {
const timeZone = new Temporal.TimeZone("UTC");
const zonedDateTime = new Temporal.ZonedDateTime(1625614921000000000n, timeZone);
expect(zonedDateTime.epochSeconds).toBe(1625614921);
});
});
test("errors", () => {
test("this value must be a Temporal.ZonedDateTime object", () => {
expect(() => {
Reflect.get(Temporal.ZonedDateTime.prototype, "epochSeconds", "foo");
}).toThrowWithMessage(TypeError, "Not a Temporal.ZonedDateTime");
});
});