TimeZone.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. /*
  2. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/DateTimeLexer.h>
  7. #include <AK/Time.h>
  8. #include <LibCrypto/BigInt/UnsignedBigInteger.h>
  9. #include <LibJS/Runtime/AbstractOperations.h>
  10. #include <LibJS/Runtime/Date.h>
  11. #include <LibJS/Runtime/GlobalObject.h>
  12. #include <LibJS/Runtime/IteratorOperations.h>
  13. #include <LibJS/Runtime/Temporal/AbstractOperations.h>
  14. #include <LibJS/Runtime/Temporal/Instant.h>
  15. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  16. #include <LibJS/Runtime/Temporal/TimeZone.h>
  17. #include <LibJS/Runtime/Temporal/TimeZoneConstructor.h>
  18. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  19. #include <LibTimeZone/TimeZone.h>
  20. namespace JS::Temporal {
  21. // 11 Temporal.TimeZone Objects, https://tc39.es/proposal-temporal/#sec-temporal-timezone-objects
  22. TimeZone::TimeZone(String identifier, Object& prototype)
  23. : Object(prototype)
  24. , m_identifier(move(identifier))
  25. {
  26. }
  27. // 11.1.1 IsValidTimeZoneName ( timeZone ), https://tc39.es/proposal-temporal/#sec-isvalidtimezonename
  28. // 15.1.1 IsValidTimeZoneName ( timeZone ), https://tc39.es/proposal-temporal/#sup-isvalidtimezonename
  29. bool is_valid_time_zone_name(String const& time_zone)
  30. {
  31. // 1. If one of the Zone or Link names of the IANA Time Zone Database is an ASCII-case-insensitive match of timeZone as described in 6.1, return true.
  32. // 2. If timeZone is an ASCII-case-insensitive match of "UTC", return true.
  33. // 3. Return false.
  34. // NOTE: When LibTimeZone is built without ENABLE_TIME_ZONE_DATA, this only recognizes 'UTC',
  35. // which matches the minimum requirements of the Temporal spec.
  36. return ::TimeZone::time_zone_from_string(time_zone).has_value();
  37. }
  38. // 11.1.2 CanonicalizeTimeZoneName ( timeZone ), https://tc39.es/proposal-temporal/#sec-canonicalizetimezonename
  39. // 15.1.2 CanonicalizeTimeZoneName ( timeZone ), https://tc39.es/proposal-temporal/#sup-canonicalizetimezonename
  40. String canonicalize_time_zone_name(String const& time_zone)
  41. {
  42. // 1. Let ianaTimeZone be the String value of the Zone or Link name of the IANA Time Zone Database that is an ASCII-case-insensitive match of timeZone as described in 6.1.
  43. // 2. If ianaTimeZone is a Link name, let ianaTimeZone be the String value of the corresponding Zone name as specified in the file backward of the IANA Time Zone Database.
  44. auto iana_time_zone = ::TimeZone::canonicalize_time_zone(time_zone);
  45. // 3. If ianaTimeZone is "Etc/UTC" or "Etc/GMT", return "UTC".
  46. // NOTE: This is already done in canonicalize_time_zone().
  47. // 4. Return ianaTimeZone.
  48. return *iana_time_zone;
  49. }
  50. // 11.1.3 DefaultTimeZone ( ), https://tc39.es/proposal-temporal/#sec-defaulttimezone
  51. // NOTE: This is the minimum implementation of DefaultTimeZone, supporting only the "UTC" time zone.
  52. String default_time_zone()
  53. {
  54. // 1. Return "UTC".
  55. return "UTC";
  56. }
  57. // 11.6.1 ParseTemporalTimeZone ( string ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporaltimezone
  58. ThrowCompletionOr<String> parse_temporal_time_zone(GlobalObject& global_object, String const& string)
  59. {
  60. // 1. Assert: Type(string) is String.
  61. // 2. Let result be ? ParseTemporalTimeZoneString(string).
  62. auto result = TRY(parse_temporal_time_zone_string(global_object, string));
  63. // 3. If result.[[Name]] is not undefined, return result.[[Name]].
  64. if (result.name.has_value())
  65. return *result.name;
  66. // 4. If result.[[Z]] is true, return "UTC".
  67. if (result.z)
  68. return String { "UTC" };
  69. // 5. Return result.[[OffsetString]].
  70. return *result.offset;
  71. }
  72. // 11.6.2 CreateTemporalTimeZone ( identifier [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporaltimezone
  73. ThrowCompletionOr<TimeZone*> create_temporal_time_zone(GlobalObject& global_object, String const& identifier, FunctionObject const* new_target)
  74. {
  75. // 1. If newTarget is not present, set it to %Temporal.TimeZone%.
  76. if (!new_target)
  77. new_target = global_object.temporal_time_zone_constructor();
  78. // 2. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.TimeZone.prototype%", « [[InitializedTemporalTimeZone]], [[Identifier]], [[OffsetNanoseconds]] »).
  79. // 3. Set object.[[Identifier]] to identifier.
  80. auto* object = TRY(ordinary_create_from_constructor<TimeZone>(global_object, *new_target, &GlobalObject::temporal_time_zone_prototype, identifier));
  81. // 4. If identifier satisfies the syntax of a TimeZoneNumericUTCOffset (see 13.33), then
  82. if (is_valid_time_zone_numeric_utc_offset_syntax(identifier)) {
  83. // a. Set object.[[OffsetNanoseconds]] to ! ParseTimeZoneOffsetString(identifier).
  84. object->set_offset_nanoseconds(TRY(parse_time_zone_offset_string(global_object, identifier)));
  85. }
  86. // 5. Else,
  87. else {
  88. // a. Assert: ! CanonicalizeTimeZoneName(identifier) is identifier.
  89. VERIFY(canonicalize_time_zone_name(identifier) == identifier);
  90. // b. Set object.[[OffsetNanoseconds]] to undefined.
  91. // NOTE: No-op.
  92. }
  93. // 6. Return object.
  94. return object;
  95. }
  96. // 11.6.3 GetISOPartsFromEpoch ( epochNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-getisopartsfromepoch
  97. ISODateTime get_iso_parts_from_epoch(BigInt const& epoch_nanoseconds)
  98. {
  99. // 1. Assert: epochNanoseconds is an integer.
  100. // 2. Let remainderNs be epochNanoseconds modulo 10^6.
  101. auto remainder_ns_bigint = modulo(epoch_nanoseconds.big_integer(), Crypto::UnsignedBigInteger { 1'000'000 });
  102. auto remainder_ns = remainder_ns_bigint.to_double();
  103. // 3. Let epochMilliseconds be (epochNanoseconds − remainderNs) / 10^6.
  104. auto epoch_milliseconds_bigint = epoch_nanoseconds.big_integer().minus(remainder_ns_bigint).divided_by(Crypto::UnsignedBigInteger { 1'000'000 }).quotient;
  105. auto epoch_milliseconds = epoch_milliseconds_bigint.to_double();
  106. // 4. Let year be ! YearFromTime(epochMilliseconds).
  107. auto year = year_from_time(epoch_milliseconds);
  108. // 5. Let month be ! MonthFromTime(epochMilliseconds) + 1.
  109. auto month = static_cast<u8>(month_from_time(epoch_milliseconds) + 1);
  110. // 6. Let day be ! DateFromTime(epochMilliseconds).
  111. auto day = date_from_time(epoch_milliseconds);
  112. // 7. Let hour be ! HourFromTime(epochMilliseconds).
  113. auto hour = hour_from_time(epoch_milliseconds);
  114. // 8. Let minute be ! MinFromTime(epochMilliseconds).
  115. auto minute = min_from_time(epoch_milliseconds);
  116. // 9. Let second be ! SecFromTime(epochMilliseconds).
  117. auto second = sec_from_time(epoch_milliseconds);
  118. // 10. Let millisecond be ! msFromTime(epochMilliseconds).
  119. auto millisecond = ms_from_time(epoch_milliseconds);
  120. // 11. Let microsecond be floor(remainderNs / 1000) modulo 1000.
  121. auto microsecond = modulo(floor(remainder_ns / 1000), 1000);
  122. // 12. Let nanosecond be remainderNs modulo 1000.
  123. auto nanosecond = modulo(remainder_ns, 1000);
  124. // 13. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day, [[Hour]]: hour, [[Minute]]: minute, [[Second]]: second, [[Millisecond]]: millisecond, [[Microsecond]]: microsecond, [[Nanosecond]]: nanosecond }.
  125. return { .year = year, .month = month, .day = day, .hour = hour, .minute = minute, .second = second, .millisecond = millisecond, .microsecond = static_cast<u16>(microsecond), .nanosecond = static_cast<u16>(nanosecond) };
  126. }
  127. // 11.6.4 GetIANATimeZoneEpochValue ( timeZoneIdentifier, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/proposal-temporal/#sec-temporal-getianatimezoneepochvalue
  128. MarkedValueList get_iana_time_zone_epoch_value(GlobalObject& global_object, [[maybe_unused]] StringView time_zone_identifier, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond)
  129. {
  130. // The abstract operation GetIANATimeZoneEpochValue is an implementation-defined algorithm that returns a List of integers. Each integer in the List represents a number of nanoseconds since the Unix epoch in UTC that may correspond to the given calendar date and wall-clock time in the IANA time zone identified by timeZoneIdentifier.
  131. // When the input represents a local time repeating multiple times at a negative time zone transition (e.g. when the daylight saving time ends or the time zone offset is decreased due to a time zone rule change), the returned List will have more than one element. When the input represents a skipped local time at a positive time zone transition (e.g. when the daylight saving time starts or the time zone offset is increased due to a time zone rule change), the returned List will be empty. Otherwise, the returned List will have one element.
  132. // FIXME: Implement this properly for non-UTC timezones.
  133. // FIXME: MarkedValueList<T> for T != Value would still be nice.
  134. auto& vm = global_object.vm();
  135. auto list = MarkedValueList { vm.heap() };
  136. list.append(get_epoch_from_iso_parts(global_object, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond));
  137. return list;
  138. }
  139. // 11.6.5 GetIANATimeZoneOffsetNanoseconds ( epochNanoseconds, timeZoneIdentifier ), https://tc39.es/proposal-temporal/#sec-temporal-getianatimezoneoffsetnanoseconds
  140. i64 get_iana_time_zone_offset_nanoseconds(BigInt const& epoch_nanoseconds, String const& time_zone_identifier)
  141. {
  142. // The abstract operation GetIANATimeZoneOffsetNanoseconds is an implementation-defined algorithm that returns an integer representing the offset of the IANA time zone identified by timeZoneIdentifier from UTC, at the instant corresponding to epochNanoseconds.
  143. // Given the same values of epochNanoseconds and timeZoneIdentifier, the result must be the same for the lifetime of the surrounding agent.
  144. // Only called with validated TimeZone [[Identifier]] as argument.
  145. auto time_zone = ::TimeZone::time_zone_from_string(time_zone_identifier);
  146. VERIFY(time_zone.has_value());
  147. // Since Time::from_seconds() and Time::from_nanoseconds() both take an i64, converting to
  148. // seconds first gives us a greater range. The TZDB doesn't have sub-second offsets.
  149. auto seconds = epoch_nanoseconds.big_integer().divided_by("1000000000"_bigint).quotient;
  150. // The provided epoch (nano)seconds value is potentially out of range for AK::Time and subsequently
  151. // get_time_zone_offset(). We can safely assume that the TZDB has no useful information that far
  152. // into the past and future anyway, so clamp it to the i64 range.
  153. Time time;
  154. if (seconds < Crypto::SignedBigInteger::create_from(NumericLimits<i64>::min()))
  155. time = Time::min();
  156. else if (seconds > Crypto::SignedBigInteger::create_from(NumericLimits<i64>::max()))
  157. time = Time::max();
  158. else
  159. time = Time::from_seconds(*seconds.to_base(10).to_int<i64>());
  160. auto offset_seconds = ::TimeZone::get_time_zone_offset(*time_zone, time);
  161. VERIFY(offset_seconds.has_value());
  162. return *offset_seconds * 1'000'000'000;
  163. }
  164. // 11.6.6 GetIANATimeZoneNextTransition ( epochNanoseconds, timeZoneIdentifier ), https://tc39.es/proposal-temporal/#sec-temporal-getianatimezonenexttransition
  165. BigInt* get_iana_time_zone_next_transition(GlobalObject&, [[maybe_unused]] BigInt const& epoch_nanoseconds, [[maybe_unused]] StringView time_zone_identifier)
  166. {
  167. // The abstract operation GetIANATimeZoneNextTransition is an implementation-defined algorithm that returns an integer representing the number of nanoseconds since the Unix epoch in UTC that corresponds to the first time zone transition after epochNanoseconds in the IANA time zone identified by timeZoneIdentifier or null if no such transition exists.
  168. // TODO: Implement this
  169. return nullptr;
  170. }
  171. // 11.6.7 GetIANATimeZonePreviousTransition ( epochNanoseconds, timeZoneIdentifier ), https://tc39.es/proposal-temporal/#sec-temporal-getianatimezoneprevioustransition
  172. BigInt* get_iana_time_zone_previous_transition(GlobalObject&, [[maybe_unused]] BigInt const& epoch_nanoseconds, [[maybe_unused]] StringView time_zone_identifier)
  173. {
  174. // The abstract operation GetIANATimeZonePreviousTransition is an implementation-defined algorithm that returns an integer representing the number of nanoseconds since the Unix epoch in UTC that corresponds to the last time zone transition before epochNanoseconds in the IANA time zone identified by timeZoneIdentifier or null if no such transition exists.
  175. // TODO: Implement this
  176. return nullptr;
  177. }
  178. // https://tc39.es/proposal-temporal/#prod-TimeZoneNumericUTCOffset
  179. static bool parse_time_zone_numeric_utc_offset_syntax(String const& offset_string, StringView& sign, StringView& hours, Optional<StringView>& minutes, Optional<StringView>& seconds, Optional<StringView>& fraction)
  180. {
  181. DateTimeLexer lexer(offset_string);
  182. auto sign_part = lexer.consume_sign();
  183. if (!sign_part.has_value())
  184. return false;
  185. sign = *sign_part;
  186. auto hours_part = lexer.consume_hours();
  187. if (!hours_part.has_value())
  188. return false;
  189. hours = *hours_part;
  190. if (!lexer.tell_remaining())
  191. return true;
  192. auto uses_separator = lexer.consume_specific(':');
  193. minutes = lexer.consume_minutes_or_seconds();
  194. if (!minutes.has_value())
  195. return false;
  196. if (!lexer.tell_remaining())
  197. return true;
  198. if (lexer.consume_specific(':') != uses_separator)
  199. return false;
  200. seconds = lexer.consume_minutes_or_seconds();
  201. if (!seconds.has_value())
  202. return false;
  203. if (!lexer.tell_remaining())
  204. return true;
  205. if (!lexer.consume_specific('.') && !lexer.consume_specific(','))
  206. return false;
  207. fraction = lexer.consume_fractional_seconds();
  208. if (!fraction.has_value())
  209. return false;
  210. return !lexer.tell_remaining();
  211. }
  212. bool is_valid_time_zone_numeric_utc_offset_syntax(String const& offset_string)
  213. {
  214. StringView discarded;
  215. Optional<StringView> optionally_discarded;
  216. // FIXME: This is very wasteful
  217. return parse_time_zone_numeric_utc_offset_syntax(offset_string, discarded, discarded, optionally_discarded, optionally_discarded, optionally_discarded);
  218. }
  219. // 11.6.8 ParseTimeZoneOffsetString ( offsetString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetimezoneoffsetstring
  220. ThrowCompletionOr<double> parse_time_zone_offset_string(GlobalObject& global_object, String const& offset_string)
  221. {
  222. auto& vm = global_object.vm();
  223. // 1. Assert: Type(offsetString) is String.
  224. // 2. If offsetString does not satisfy the syntax of a TimeZoneNumericUTCOffset (see 13.33), then
  225. // a. Throw a RangeError exception.
  226. // 3. Let sign, hours, minutes, seconds, and fraction be the parts of offsetString produced respectively by the TimeZoneUTCOffsetSign, TimeZoneUTCOffsetHour, TimeZoneUTCOffsetMinute, TimeZoneUTCOffsetSecond, and TimeZoneUTCOffsetFraction productions, or undefined if not present.
  227. StringView sign_part;
  228. StringView hours_part;
  229. Optional<StringView> minutes_part;
  230. Optional<StringView> seconds_part;
  231. Optional<StringView> fraction_part;
  232. auto success = parse_time_zone_numeric_utc_offset_syntax(offset_string, sign_part, hours_part, minutes_part, seconds_part, fraction_part);
  233. if (!success)
  234. return vm.throw_completion<RangeError>(global_object, ErrorType::InvalidFormat, "TimeZone offset");
  235. // 4. If either hours or sign are undefined, throw a RangeError exception.
  236. // NOTE: Both of these checks are always false, due to the handling of Step 2
  237. double sign;
  238. // 5. If sign is the code unit 0x002D (HYPHEN-MINUS) or 0x2212 (MINUS SIGN), then
  239. if (sign_part.is_one_of("-", "\xE2\x88\x92")) {
  240. // a. Set sign to −1.
  241. sign = -1;
  242. }
  243. // 6. Else,
  244. else {
  245. // a. Set sign to 1.
  246. sign = 1;
  247. }
  248. // 7. Set hours to ! ToIntegerOrInfinity(hours).
  249. auto hours = MUST(Value(js_string(vm, hours_part)).to_integer_or_infinity(global_object));
  250. // 8. Set minutes to ! ToIntegerOrInfinity(minutes).
  251. auto minutes = MUST(Value(js_string(vm, minutes_part.value_or(""sv))).to_integer_or_infinity(global_object));
  252. // 9. Set seconds to ! ToIntegerOrInfinity(seconds).
  253. auto seconds = MUST(Value(js_string(vm, seconds_part.value_or(""sv))).to_integer_or_infinity(global_object));
  254. double nanoseconds;
  255. // 10. If fraction is not undefined, then
  256. if (fraction_part.has_value()) {
  257. // a. Set fraction to the string-concatenation of the previous value of fraction and the string "000000000".
  258. auto fraction = String::formatted("{}000000000", *fraction_part);
  259. // b. Let nanoseconds be the String value equal to the substring of fraction consisting of the code units with indices 0 (inclusive) through 9 (exclusive).
  260. // c. Set nanoseconds to ! ToIntegerOrInfinity(nanoseconds).
  261. nanoseconds = MUST(Value(js_string(vm, fraction.substring_view(0, 9))).to_integer_or_infinity(global_object));
  262. }
  263. // 11. Else,
  264. else {
  265. // a. Let nanoseconds be 0.
  266. nanoseconds = 0;
  267. }
  268. // 12. Return sign × (((hours × 60 + minutes) × 60 + seconds) × 10^9 + nanoseconds).
  269. return sign * (((hours * 60 + minutes) * 60 + seconds) * 1000000000 + nanoseconds);
  270. }
  271. // 11.6.9 FormatTimeZoneOffsetString ( offsetNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-formattimezoneoffsetstring
  272. String format_time_zone_offset_string(double offset_nanoseconds)
  273. {
  274. auto offset = static_cast<i64>(offset_nanoseconds);
  275. // 1. Assert: offsetNanoseconds is an integer.
  276. VERIFY(offset == offset_nanoseconds);
  277. StringBuilder builder;
  278. // 2. If offsetNanoseconds ≥ 0, let sign be "+"; otherwise, let sign be "-".
  279. if (offset >= 0)
  280. builder.append('+');
  281. else
  282. builder.append('-');
  283. // 3. Let _offsetNanoseconds_ be abs(_offsetNanoseconds_).
  284. offset = AK::abs(offset);
  285. // 4. Let nanoseconds be offsetNanoseconds modulo 10^9.
  286. auto nanoseconds = offset % 1000000000;
  287. // 5. Let seconds be floor(offsetNanoseconds / 10^9) modulo 60.
  288. auto seconds = (offset / 1000000000) % 60;
  289. // 6. Let minutes be floor(offsetNanoseconds / (6 × 10^10)) modulo 60.
  290. auto minutes = (offset / 60000000000) % 60;
  291. // 7. Let hours be floor(offsetNanoseconds / (3.6 × 10^12)).
  292. auto hours = offset / 3600000000000;
  293. // 8. Let h be hours, formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  294. builder.appendff("{:02}", hours);
  295. // 9. Let m be minutes, formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  296. builder.appendff(":{:02}", minutes);
  297. // 10. Let s be seconds, formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  298. // Handled by steps 10 & 11
  299. // 11. If nanoseconds ≠ 0, then
  300. if (nanoseconds != 0) {
  301. // a. Let fraction be nanoseconds, formatted as a nine-digit decimal number, padded to the left with zeroes if necessary.
  302. // b. Set fraction to the longest possible substring of fraction starting at position 0 and not ending with the code unit 0x0030 (DIGIT ZERO).
  303. // c. Let post be the string-concatenation of the code unit 0x003A (COLON), s, the code unit 0x002E (FULL STOP), and fraction.
  304. builder.appendff(":{:02}.{}", seconds, String::formatted("{:09}", nanoseconds).trim("0"sv, TrimMode::Right));
  305. }
  306. // 12. Else if seconds ≠ 0, then
  307. else if (seconds != 0) {
  308. // a. Let post be the string-concatenation of the code unit 0x003A (COLON) and s.
  309. builder.appendff(":{:02}", seconds);
  310. }
  311. // 13. Else,
  312. // a. Let post be the empty String.
  313. // 14. Return the string-concatenation of sign, h, the code unit 0x003A (COLON), m, and post.
  314. return builder.to_string();
  315. }
  316. // 11.6.10 FormatISOTimeZoneOffsetString ( offsetNanoseconds ), https://tc39.es/proposal-temporal/#sec-temporal-formatisotimezoneoffsetstring
  317. String format_iso_time_zone_offset_string(double offset_nanoseconds)
  318. {
  319. // 1. Assert: offsetNanoseconds is an integer.
  320. VERIFY(trunc(offset_nanoseconds) == offset_nanoseconds);
  321. // 2. Set offsetNanoseconds to ! RoundNumberToIncrement(offsetNanoseconds, 60 × 10^9, "halfExpand").
  322. offset_nanoseconds = round_number_to_increment(offset_nanoseconds, 60000000000, "halfExpand"sv);
  323. // 3. If offsetNanoseconds ≥ 0, let sign be "+"; otherwise, let sign be "-".
  324. auto sign = offset_nanoseconds >= 0 ? "+"sv : "-"sv;
  325. // 4. Set offsetNanoseconds to abs(offsetNanoseconds).
  326. offset_nanoseconds = fabs(offset_nanoseconds);
  327. // 5. Let minutes be offsetNanoseconds / (60 × 10^9) modulo 60.
  328. auto minutes = fmod(offset_nanoseconds / 60000000000, 60);
  329. // 6. Let hours be floor(offsetNanoseconds / (3600 × 10^9)).
  330. auto hours = floor(offset_nanoseconds / 3600000000000);
  331. // 7. Let h be hours, formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  332. // 8. Let m be minutes, formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  333. // 9. Return the string-concatenation of sign, h, the code unit 0x003A (COLON), and m.
  334. return String::formatted("{}{:02}:{:02}", sign, (u32)hours, (u32)minutes);
  335. }
  336. // 11.6.11 ToTemporalTimeZone ( temporalTimeZoneLike ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaltimezone
  337. ThrowCompletionOr<Object*> to_temporal_time_zone(GlobalObject& global_object, Value temporal_time_zone_like)
  338. {
  339. auto& vm = global_object.vm();
  340. // 1. If Type(temporalTimeZoneLike) is Object, then
  341. if (temporal_time_zone_like.is_object()) {
  342. // a. If temporalTimeZoneLike has an [[InitializedTemporalZonedDateTime]] internal slot, then
  343. if (is<ZonedDateTime>(temporal_time_zone_like.as_object())) {
  344. auto& zoned_date_time = static_cast<ZonedDateTime&>(temporal_time_zone_like.as_object());
  345. // i. Return temporalTimeZoneLike.[[TimeZone]].
  346. return &zoned_date_time.time_zone();
  347. }
  348. // b. If ? HasProperty(temporalTimeZoneLike, "timeZone") is false, return temporalTimeZoneLike.
  349. if (!TRY(temporal_time_zone_like.as_object().has_property(vm.names.timeZone)))
  350. return &temporal_time_zone_like.as_object();
  351. // c. Set temporalTimeZoneLike to ? Get(temporalTimeZoneLike, "timeZone").
  352. temporal_time_zone_like = TRY(temporal_time_zone_like.as_object().get(vm.names.timeZone));
  353. // d. If Type(temporalTimeZoneLike) is Object and ? HasProperty(temporalTimeZoneLike, "timeZone") is false, return temporalTimeZoneLike.
  354. if (temporal_time_zone_like.is_object() && !TRY(temporal_time_zone_like.as_object().has_property(vm.names.timeZone)))
  355. return &temporal_time_zone_like.as_object();
  356. }
  357. // 2. Let identifier be ? ToString(temporalTimeZoneLike).
  358. auto identifier = TRY(temporal_time_zone_like.to_string(global_object));
  359. // 3. Let result be ? ParseTemporalTimeZone(identifier).
  360. auto result = TRY(parse_temporal_time_zone(global_object, identifier));
  361. // 4. Return ? CreateTemporalTimeZone(result).
  362. return TRY(create_temporal_time_zone(global_object, result));
  363. }
  364. // 11.6.12 GetOffsetNanosecondsFor ( timeZone, instant ), https://tc39.es/proposal-temporal/#sec-temporal-getoffsetnanosecondsfor
  365. ThrowCompletionOr<double> get_offset_nanoseconds_for(GlobalObject& global_object, Value time_zone, Instant& instant)
  366. {
  367. auto& vm = global_object.vm();
  368. // 1. Let getOffsetNanosecondsFor be ? GetMethod(timeZone, "getOffsetNanosecondsFor").
  369. auto* get_offset_nanoseconds_for = TRY(time_zone.get_method(global_object, vm.names.getOffsetNanosecondsFor));
  370. // 2. Let offsetNanoseconds be ? Call(getOffsetNanosecondsFor, timeZone, « instant »).
  371. auto offset_nanoseconds_value = TRY(call(global_object, get_offset_nanoseconds_for, time_zone, &instant));
  372. // 3. If Type(offsetNanoseconds) is not Number, throw a TypeError exception.
  373. if (!offset_nanoseconds_value.is_number())
  374. return vm.throw_completion<TypeError>(global_object, ErrorType::IsNotA, "Offset nanoseconds value", "number");
  375. // 4. If ! IsIntegralNumber(offsetNanoseconds) is false, throw a RangeError exception.
  376. if (!offset_nanoseconds_value.is_integral_number())
  377. return vm.throw_completion<RangeError>(global_object, ErrorType::IsNotAn, "Offset nanoseconds value", "integral number");
  378. // 5. Set offsetNanoseconds to ℝ(offsetNanoseconds).
  379. auto offset_nanoseconds = offset_nanoseconds_value.as_double();
  380. // 6. If abs(offsetNanoseconds) > 86400 × 10^9, throw a RangeError exception.
  381. if (fabs(offset_nanoseconds) > 86400000000000.0)
  382. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidOffsetNanosecondsValue);
  383. // 7. Return offsetNanoseconds.
  384. return offset_nanoseconds;
  385. }
  386. // 11.6.13 BuiltinTimeZoneGetOffsetStringFor ( timeZone, instant ), https://tc39.es/proposal-temporal/#sec-temporal-builtintimezonegetoffsetstringfor
  387. ThrowCompletionOr<String> builtin_time_zone_get_offset_string_for(GlobalObject& global_object, Value time_zone, Instant& instant)
  388. {
  389. // 1. Let offsetNanoseconds be ? GetOffsetNanosecondsFor(timeZone, instant).
  390. auto offset_nanoseconds = TRY(get_offset_nanoseconds_for(global_object, time_zone, instant));
  391. // 2. Return ! FormatTimeZoneOffsetString(offsetNanoseconds).
  392. return format_time_zone_offset_string(offset_nanoseconds);
  393. }
  394. // 11.6.14 BuiltinTimeZoneGetPlainDateTimeFor ( timeZone, instant, calendar ), https://tc39.es/proposal-temporal/#sec-temporal-builtintimezonegetplaindatetimefor
  395. ThrowCompletionOr<PlainDateTime*> builtin_time_zone_get_plain_date_time_for(GlobalObject& global_object, Value time_zone, Instant& instant, Object& calendar)
  396. {
  397. // 1. Assert: instant has an [[InitializedTemporalInstant]] internal slot.
  398. // 2. Let offsetNanoseconds be ? GetOffsetNanosecondsFor(timeZone, instant).
  399. auto offset_nanoseconds = TRY(get_offset_nanoseconds_for(global_object, time_zone, instant));
  400. // 3. Let result be ! GetISOPartsFromEpoch(instant.[[Nanoseconds]]).
  401. auto result = get_iso_parts_from_epoch(instant.nanoseconds());
  402. // 4. Set result to ! BalanceISODateTime(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]] + offsetNanoseconds).
  403. result = balance_iso_date_time(result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond + offset_nanoseconds);
  404. // 5. Return ? CreateTemporalDateTime(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]], calendar).
  405. return create_temporal_date_time(global_object, result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond, calendar);
  406. }
  407. // 11.6.15 BuiltinTimeZoneGetInstantFor ( timeZone, dateTime, disambiguation ), https://tc39.es/proposal-temporal/#sec-temporal-builtintimezonegetinstantfor
  408. ThrowCompletionOr<Instant*> builtin_time_zone_get_instant_for(GlobalObject& global_object, Value time_zone, PlainDateTime& date_time, StringView disambiguation)
  409. {
  410. // 1. Assert: dateTime has an [[InitializedTemporalDateTime]] internal slot.
  411. // 2. Let possibleInstants be ? GetPossibleInstantsFor(timeZone, dateTime).
  412. auto possible_instants = TRY(get_possible_instants_for(global_object, time_zone, date_time));
  413. // 3. Return ? DisambiguatePossibleInstants(possibleInstants, timeZone, dateTime, disambiguation).
  414. return disambiguate_possible_instants(global_object, possible_instants, time_zone, date_time, disambiguation);
  415. }
  416. // 11.6.16 DisambiguatePossibleInstants ( possibleInstants, timeZone, dateTime, disambiguation ), https://tc39.es/proposal-temporal/#sec-temporal-disambiguatepossibleinstants
  417. ThrowCompletionOr<Instant*> disambiguate_possible_instants(GlobalObject& global_object, Vector<Value> const& possible_instants, Value time_zone, PlainDateTime& date_time, StringView disambiguation)
  418. {
  419. // TODO: MarkedValueList<T> would be nice, then we could pass a Vector<Instant*> here and wouldn't need the casts...
  420. auto& vm = global_object.vm();
  421. // 1. Assert: dateTime has an [[InitializedTemporalDateTime]] internal slot.
  422. // 2. Let n be possibleInstants's length.
  423. auto n = possible_instants.size();
  424. // 3. If n = 1, then
  425. if (n == 1) {
  426. // a. Return possibleInstants[0].
  427. auto& instant = possible_instants[0];
  428. return &static_cast<Instant&>(const_cast<Object&>(instant.as_object()));
  429. }
  430. // 4. If n ≠ 0, then
  431. if (n != 0) {
  432. // a. If disambiguation is "earlier" or "compatible", then
  433. if (disambiguation.is_one_of("earlier"sv, "compatible"sv)) {
  434. // i. Return possibleInstants[0].
  435. auto& instant = possible_instants[0];
  436. return &static_cast<Instant&>(const_cast<Object&>(instant.as_object()));
  437. }
  438. // b. If disambiguation is "later", then
  439. if (disambiguation == "later"sv) {
  440. // i. Return possibleInstants[n − 1].
  441. auto& instant = possible_instants[n - 1];
  442. return &static_cast<Instant&>(const_cast<Object&>(instant.as_object()));
  443. }
  444. // c. Assert: disambiguation is "reject".
  445. VERIFY(disambiguation == "reject"sv);
  446. // d. Throw a RangeError exception.
  447. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalDisambiguatePossibleInstantsRejectMoreThanOne);
  448. }
  449. // 5. Assert: n = 0.
  450. VERIFY(n == 0);
  451. // 6. If disambiguation is "reject", then
  452. if (disambiguation == "reject"sv) {
  453. // a. Throw a RangeError exception.
  454. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalDisambiguatePossibleInstantsRejectZero);
  455. }
  456. // 7. Let epochNanoseconds be ! GetEpochFromISOParts(dateTime.[[ISOYear]], dateTime.[[ISOMonth]], dateTime.[[ISODay]], dateTime.[[ISOHour]], dateTime.[[ISOMinute]], dateTime.[[ISOSecond]], dateTime.[[ISOMillisecond]], dateTime.[[ISOMicrosecond]], dateTime.[[ISONanosecond]]).
  457. auto* epoch_nanoseconds = get_epoch_from_iso_parts(global_object, date_time.iso_year(), date_time.iso_month(), date_time.iso_day(), date_time.iso_hour(), date_time.iso_minute(), date_time.iso_second(), date_time.iso_millisecond(), date_time.iso_microsecond(), date_time.iso_nanosecond());
  458. // 8. Let dayBefore be ! CreateTemporalInstant(epochNanoseconds − 8.64 × 10^13).
  459. auto* day_before = MUST(create_temporal_instant(global_object, *js_bigint(vm, epoch_nanoseconds->big_integer().minus("86400000000000"_sbigint))));
  460. // 9. Let dayAfter be ! CreateTemporalInstant(epochNanoseconds + 8.64 × 10^13).
  461. auto* day_after = MUST(create_temporal_instant(global_object, *js_bigint(vm, epoch_nanoseconds->big_integer().plus("86400000000000"_sbigint))));
  462. // 10. Let offsetBefore be ? GetOffsetNanosecondsFor(timeZone, dayBefore).
  463. auto offset_before = TRY(get_offset_nanoseconds_for(global_object, time_zone, *day_before));
  464. // 11. Let offsetAfter be ? GetOffsetNanosecondsFor(timeZone, dayAfter).
  465. auto offset_after = TRY(get_offset_nanoseconds_for(global_object, time_zone, *day_after));
  466. // 12. Let nanoseconds be offsetAfter − offsetBefore.
  467. auto nanoseconds = offset_after - offset_before;
  468. // 13. If disambiguation is "earlier", then
  469. if (disambiguation == "earlier"sv) {
  470. // a. Let earlier be ? AddDateTime(dateTime.[[ISOYear]], dateTime.[[ISOMonth]], dateTime.[[ISODay]], dateTime.[[ISOHour]], dateTime.[[ISOMinute]], dateTime.[[ISOSecond]], dateTime.[[ISOMillisecond]], dateTime.[[ISOMicrosecond]], dateTime.[[ISONanosecond]], dateTime.[[Calendar]], 0, 0, 0, 0, 0, 0, 0, 0, 0, −nanoseconds, undefined).
  471. auto earlier = TRY(add_date_time(global_object, date_time.iso_year(), date_time.iso_month(), date_time.iso_day(), date_time.iso_hour(), date_time.iso_minute(), date_time.iso_second(), date_time.iso_millisecond(), date_time.iso_microsecond(), date_time.iso_nanosecond(), date_time.calendar(), 0, 0, 0, 0, 0, 0, 0, 0, 0, -nanoseconds, nullptr));
  472. // b. Let earlierDateTime be ! CreateTemporalDateTime(earlier.[[Year]], earlier.[[Month]], earlier.[[Day]], earlier.[[Hour]], earlier.[[Minute]], earlier.[[Second]], earlier.[[Millisecond]], earlier.[[Microsecond]], earlier.[[Nanosecond]], dateTime.[[Calendar]]).
  473. auto* earlier_date_time = MUST(create_temporal_date_time(global_object, earlier.year, earlier.month, earlier.day, earlier.hour, earlier.minute, earlier.second, earlier.millisecond, earlier.microsecond, earlier.nanosecond, date_time.calendar()));
  474. // c. Set possibleInstants to ? GetPossibleInstantsFor(timeZone, earlierDateTime).
  475. auto possible_instants_mvl = TRY(get_possible_instants_for(global_object, time_zone, *earlier_date_time));
  476. // d. If possibleInstants is empty, throw a RangeError exception.
  477. if (possible_instants_mvl.is_empty())
  478. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalDisambiguatePossibleInstantsEarlierZero);
  479. // e. Return possibleInstants[0].
  480. auto& instant = possible_instants_mvl[0];
  481. return &static_cast<Instant&>(const_cast<Object&>(instant.as_object()));
  482. }
  483. // 14. Assert: disambiguation is "compatible" or "later".
  484. VERIFY(disambiguation.is_one_of("compatible"sv, "later"sv));
  485. // 15. Let later be ? AddDateTime(dateTime.[[ISOYear]], dateTime.[[ISOMonth]], dateTime.[[ISODay]], dateTime.[[ISOHour]], dateTime.[[ISOMinute]], dateTime.[[ISOSecond]], dateTime.[[ISOMillisecond]], dateTime.[[ISOMicrosecond]], dateTime.[[ISONanosecond]], dateTime.[[Calendar]], 0, 0, 0, 0, 0, 0, 0, 0, 0, nanoseconds, undefined).
  486. auto later = TRY(add_date_time(global_object, date_time.iso_year(), date_time.iso_month(), date_time.iso_day(), date_time.iso_hour(), date_time.iso_minute(), date_time.iso_second(), date_time.iso_millisecond(), date_time.iso_microsecond(), date_time.iso_nanosecond(), date_time.calendar(), 0, 0, 0, 0, 0, 0, 0, 0, 0, nanoseconds, nullptr));
  487. // 16. Let laterDateTime be ! CreateTemporalDateTime(later.[[Year]], later.[[Month]], later.[[Day]], later.[[Hour]], later.[[Minute]], later.[[Second]], later.[[Millisecond]], later.[[Microsecond]], later.[[Nanosecond]], dateTime.[[Calendar]]).
  488. auto* later_date_time = MUST(create_temporal_date_time(global_object, later.year, later.month, later.day, later.hour, later.minute, later.second, later.millisecond, later.microsecond, later.nanosecond, date_time.calendar()));
  489. // 17. Set possibleInstants to ? GetPossibleInstantsFor(timeZone, laterDateTime).
  490. auto possible_instants_mvl = TRY(get_possible_instants_for(global_object, time_zone, *later_date_time));
  491. // 18. Set n to possibleInstants's length.
  492. n = possible_instants_mvl.size();
  493. // 19. If n = 0, throw a RangeError exception.
  494. if (n == 0)
  495. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalDisambiguatePossibleInstantsZero);
  496. // 20. Return possibleInstants[n − 1].
  497. auto& instant = possible_instants_mvl[n - 1];
  498. return &static_cast<Instant&>(const_cast<Object&>(instant.as_object()));
  499. }
  500. // 11.6.17 GetPossibleInstantsFor ( timeZone, dateTime ), https://tc39.es/proposal-temporal/#sec-temporal-getpossibleinstantsfor
  501. ThrowCompletionOr<MarkedValueList> get_possible_instants_for(GlobalObject& global_object, Value time_zone, PlainDateTime& date_time)
  502. {
  503. auto& vm = global_object.vm();
  504. // 1. Assert: dateTime has an [[InitializedTemporalDateTime]] internal slot.
  505. // 2. Let possibleInstants be ? Invoke(timeZone, "getPossibleInstantsFor", « dateTime »).
  506. auto possible_instants = TRY(time_zone.invoke(global_object, vm.names.getPossibleInstantsFor, &date_time));
  507. // 3. Let iteratorRecord be ? GetIterator(possibleInstants, sync).
  508. auto iterator = TRY(get_iterator(global_object, possible_instants, IteratorHint::Sync));
  509. // 4. Let list be a new empty List.
  510. auto list = MarkedValueList { vm.heap() };
  511. // 5. Let next be true.
  512. Object* next = nullptr;
  513. // 6. Repeat, while next is not false,
  514. do {
  515. // a. Set next to ? IteratorStep(iteratorRecord).
  516. next = TRY(iterator_step(global_object, iterator));
  517. // b. If next is not false, then
  518. if (next) {
  519. // i. Let nextValue be ? IteratorValue(next).
  520. auto next_value = TRY(iterator_value(global_object, *next));
  521. // ii. If Type(nextValue) is not Object or nextValue does not have an [[InitializedTemporalInstant]] internal slot, then
  522. if (!next_value.is_object() || !is<Instant>(next_value.as_object())) {
  523. // 1. Let completion be ThrowCompletion(a newly created TypeError object).
  524. auto completion = vm.throw_completion<TypeError>(global_object, ErrorType::NotAnObjectOfType, "Temporal.Instant");
  525. // 2. Return ? IteratorClose(iteratorRecord, completion).
  526. return iterator_close(global_object, iterator, move(completion));
  527. }
  528. // iii. Append nextValue to the end of the List list.
  529. list.append(next_value);
  530. }
  531. } while (next != nullptr);
  532. // 7. Return list.
  533. return { move(list) };
  534. }
  535. // 11.6.18 TimeZoneEquals ( one, two ), https://tc39.es/proposal-temporal/#sec-temporal-timezoneequals
  536. ThrowCompletionOr<bool> time_zone_equals(GlobalObject& global_object, Object& one, Object& two)
  537. {
  538. // 1. If one and two are the same Object value, return true.
  539. if (&one == &two)
  540. return true;
  541. // 2. Let timeZoneOne be ? ToString(one).
  542. auto time_zone_one = TRY(Value(&one).to_string(global_object));
  543. // 3. Let timeZoneTwo be ? ToString(two).
  544. auto time_zone_two = TRY(Value(&two).to_string(global_object));
  545. // 4. If timeZoneOne is timeZoneTwo, return true.
  546. if (time_zone_one == time_zone_two)
  547. return true;
  548. // 5. Return false.
  549. return false;
  550. }
  551. }