From 6576d0291cf5900a1e4b777dbc17287629cea259 Mon Sep 17 00:00:00 2001 From: Timothy Flynn Date: Sat, 15 Jan 2022 00:48:49 -0500 Subject: [PATCH] LibJS: Implement Date.prototype.getTimezoneOffset --- .../Libraries/LibJS/Runtime/DatePrototype.cpp | 10 ++++--- .../Date/Date.prototype.getTimezoneOffset.js | 30 +++++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) create mode 100644 Userland/Libraries/LibJS/Tests/builtins/Date/Date.prototype.getTimezoneOffset.js diff --git a/Userland/Libraries/LibJS/Runtime/DatePrototype.cpp b/Userland/Libraries/LibJS/Runtime/DatePrototype.cpp index 713d2f42430..b43a3a14e60 100644 --- a/Userland/Libraries/LibJS/Runtime/DatePrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/DatePrototype.cpp @@ -245,13 +245,15 @@ JS_DEFINE_NATIVE_FUNCTION(DatePrototype::get_time) // 21.4.4.11 Date.prototype.getTimezoneOffset ( ), https://tc39.es/ecma262/#sec-date.prototype.gettimezoneoffset JS_DEFINE_NATIVE_FUNCTION(DatePrototype::get_timezone_offset) { - auto* this_object = TRY(typed_this_object(global_object)); + // 1. Let t be ? thisTimeValue(this value). + auto time = TRY(this_time_value(global_object, vm.this_value(global_object))); - if (!Value(this_object->date_value()).is_finite_number()) + // 2. If t is NaN, return NaN. + if (time.is_nan()) return js_nan(); - // FIXME: Make this actually do something once we support timezones instead of just UTC - return Value(0); + // 3. Return (t - LocalTime(t)) / msPerMinute. + return Value((time.as_double() - local_time(time.as_double())) / Date::ms_per_minute); } // 21.4.4.12 Date.prototype.getUTCDate ( ), https://tc39.es/ecma262/#sec-date.prototype.getutcdate diff --git a/Userland/Libraries/LibJS/Tests/builtins/Date/Date.prototype.getTimezoneOffset.js b/Userland/Libraries/LibJS/Tests/builtins/Date/Date.prototype.getTimezoneOffset.js new file mode 100644 index 00000000000..74432f9fdde --- /dev/null +++ b/Userland/Libraries/LibJS/Tests/builtins/Date/Date.prototype.getTimezoneOffset.js @@ -0,0 +1,30 @@ +describe("errors", () => { + test("called on non-Date object", () => { + expect(() => { + Date.prototype.getTimezoneOffset(); + }).toThrowWithMessage(TypeError, "Not an object of type Date"); + }); +}); + +describe("correct behavior", () => { + test("NaN", () => { + const d = new Date(NaN); + expect(d.getTimezoneOffset()).toBeNaN(); + }); + + test("time clip", () => { + const d = new Date(-8.65e15); + expect(d.getTimezoneOffset()).toBeNaN(); + }); + + test("basic functionality", () => { + // Exact return values from getTimezoneOffset depend on the time zone of the host machine. + // So we can't test exact values, but that value should not change here. + const d0 = new Date(Date.parse("1989-01-23T14:30-00:00")); + const d1 = new Date(Date.parse("1989-01-23T14:30-05:00")); + + const offset0 = d0.getTimezoneOffset(); + const offset1 = d1.getTimezoneOffset(); + expect(offset0).toBe(offset1); + }); +});