ZonedDateTime.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. /*
  2. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/Date.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. #include <LibJS/Runtime/Temporal/Calendar.h>
  11. #include <LibJS/Runtime/Temporal/Duration.h>
  12. #include <LibJS/Runtime/Temporal/Instant.h>
  13. #include <LibJS/Runtime/Temporal/PlainDate.h>
  14. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  15. #include <LibJS/Runtime/Temporal/TimeZone.h>
  16. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  17. #include <LibJS/Runtime/Temporal/ZonedDateTimeConstructor.h>
  18. namespace JS::Temporal {
  19. // 6 Temporal.ZonedDateTime Objects, https://tc39.es/proposal-temporal/#sec-temporal-zoneddatetime-objects
  20. ZonedDateTime::ZonedDateTime(BigInt const& nanoseconds, Object& time_zone, Object& calendar, Object& prototype)
  21. : Object(prototype)
  22. , m_nanoseconds(nanoseconds)
  23. , m_time_zone(time_zone)
  24. , m_calendar(calendar)
  25. {
  26. }
  27. void ZonedDateTime::visit_edges(Cell::Visitor& visitor)
  28. {
  29. Base::visit_edges(visitor);
  30. visitor.visit(&m_nanoseconds);
  31. visitor.visit(&m_time_zone);
  32. visitor.visit(&m_calendar);
  33. }
  34. // 6.5.1 InterpretISODateTimeOffset ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, offsetBehaviour, offsetNanoseconds, timeZone, disambiguation, offsetOption, matchBehaviour ), https://tc39.es/proposal-temporal/#sec-temporal-interpretisodatetimeoffset
  35. ThrowCompletionOr<BigInt const*> interpret_iso_date_time_offset(GlobalObject& global_object, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond, OffsetBehavior offset_behavior, double offset_nanoseconds, Value time_zone, StringView disambiguation, StringView offset_option, MatchBehavior match_behavior)
  36. {
  37. auto& vm = global_object.vm();
  38. // 1. Let calendar be ! GetISO8601Calendar().
  39. auto* calendar = get_iso8601_calendar(global_object);
  40. // 2. Let dateTime be ? CreateTemporalDateTime(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, calendar).
  41. auto* date_time = TRY(create_temporal_date_time(global_object, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, *calendar));
  42. // 3. If offsetBehaviour is wall or offsetOption is "ignore", then
  43. if (offset_behavior == OffsetBehavior::Wall || offset_option == "ignore"sv) {
  44. // a. Let instant be ? BuiltinTimeZoneGetInstantFor(timeZone, dateTime, disambiguation).
  45. auto* instant = TRY(builtin_time_zone_get_instant_for(global_object, time_zone, *date_time, disambiguation));
  46. // b. Return instant.[[Nanoseconds]].
  47. return &instant->nanoseconds();
  48. }
  49. // 4. If offsetBehaviour is exact or offsetOption is "use", then
  50. if (offset_behavior == OffsetBehavior::Exact || offset_option == "use"sv) {
  51. // a. Let epochNanoseconds be GetEpochFromISOParts(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond).
  52. auto* epoch_nanoseconds = get_epoch_from_iso_parts(global_object, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond);
  53. // b. Set epochNanoseconds to epochNanoseconds - ℤ(offsetNanoseconds).
  54. // FIXME: Narrowing conversion from 'double' to 'i64'
  55. auto offset_nanoseconds_bigint = Crypto::SignedBigInteger::create_from((i64)offset_nanoseconds);
  56. epoch_nanoseconds = js_bigint(vm, epoch_nanoseconds->big_integer().minus(offset_nanoseconds_bigint));
  57. // c. If ! IsValidEpochNanoseconds(epochNanoseconds) is false, throw a RangeError exception.
  58. if (!is_valid_epoch_nanoseconds(*epoch_nanoseconds))
  59. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidEpochNanoseconds);
  60. // d. Return epochNanoseconds.
  61. return epoch_nanoseconds;
  62. }
  63. // 5. Assert: offsetBehaviour is option.
  64. VERIFY(offset_behavior == OffsetBehavior::Option);
  65. // 6. Assert: offsetOption is "prefer" or "reject".
  66. VERIFY(offset_option.is_one_of("prefer"sv, "reject"sv));
  67. // 7. Let possibleInstants be ? GetPossibleInstantsFor(timeZone, dateTime).
  68. auto possible_instants = TRY(get_possible_instants_for(global_object, time_zone, *date_time));
  69. // 8. For each element candidate of possibleInstants, do
  70. for (auto* candidate : possible_instants) {
  71. // a. Let candidateNanoseconds be ? GetOffsetNanosecondsFor(timeZone, candidate).
  72. auto candidate_nanoseconds = TRY(get_offset_nanoseconds_for(global_object, time_zone, *candidate));
  73. // b. If candidateNanoseconds = offsetNanoseconds, then
  74. if (candidate_nanoseconds == offset_nanoseconds) {
  75. // i. Return candidate.[[Nanoseconds]].
  76. return &candidate->nanoseconds();
  77. }
  78. // c. If matchBehaviour is match minutes, then
  79. if (match_behavior == MatchBehavior::MatchMinutes) {
  80. // i. Let roundedCandidateNanoseconds be RoundNumberToIncrement(candidateNanoseconds, 60 × 10^9, "halfExpand").
  81. auto rounded_candidate_nanoseconds = round_number_to_increment(candidate_nanoseconds, 60000000000, "halfExpand"sv);
  82. // ii. If roundedCandidateNanoseconds = offsetNanoseconds, then
  83. if (rounded_candidate_nanoseconds == offset_nanoseconds) {
  84. // 1. Return candidate.[[Nanoseconds]].
  85. return &candidate->nanoseconds();
  86. }
  87. }
  88. }
  89. // 9. If offsetOption is "reject", throw a RangeError exception.
  90. if (offset_option == "reject"sv)
  91. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidZonedDateTimeOffset);
  92. // 10. Let instant be ? DisambiguatePossibleInstants(possibleInstants, timeZone, dateTime, disambiguation).
  93. auto* instant = TRY(disambiguate_possible_instants(global_object, possible_instants, time_zone, *date_time, disambiguation));
  94. // 11. Return instant.[[Nanoseconds]].
  95. return &instant->nanoseconds();
  96. }
  97. // 6.5.2 ToTemporalZonedDateTime ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalzoneddatetime
  98. ThrowCompletionOr<ZonedDateTime*> to_temporal_zoned_date_time(GlobalObject& global_object, Value item, Object const* options)
  99. {
  100. auto& vm = global_object.vm();
  101. // 1. If options is not present, set options to undefined.
  102. // 2. Assert: Type(options) is Object or Undefined.
  103. // 3. Let offsetBehaviour be option.
  104. auto offset_behavior = OffsetBehavior::Option;
  105. // 4. Let matchBehaviour be match exactly.
  106. auto match_behavior = MatchBehavior::MatchExactly;
  107. Object* calendar = nullptr;
  108. Object* time_zone = nullptr;
  109. Optional<String> offset_string;
  110. ISODateTime result;
  111. // 5. If Type(item) is Object, then
  112. if (item.is_object()) {
  113. auto& item_object = item.as_object();
  114. // a. If item has an [[InitializedTemporalZonedDateTime]] internal slot, then
  115. if (is<ZonedDateTime>(item_object)) {
  116. // i. Return item.
  117. return &static_cast<ZonedDateTime&>(item_object);
  118. }
  119. // b. Let calendar be ? GetTemporalCalendarWithISODefault(item).
  120. calendar = TRY(get_temporal_calendar_with_iso_default(global_object, item_object));
  121. // c. Let fieldNames be ? CalendarFields(calendar, « "day", "hour", "microsecond", "millisecond", "minute", "month", "monthCode", "nanosecond", "second", "year" »).
  122. auto field_names = TRY(calendar_fields(global_object, *calendar, { "day"sv, "hour"sv, "microsecond"sv, "millisecond"sv, "minute"sv, "month"sv, "monthCode"sv, "nanosecond"sv, "second"sv, "year"sv }));
  123. // d. Append "timeZone" to fieldNames.
  124. field_names.append("timeZone");
  125. // e. Append "offset" to fieldNames.
  126. field_names.append("offset");
  127. // f. Let fields be ? PrepareTemporalFields(item, fieldNames, « "timeZone" »).
  128. auto* fields = TRY(prepare_temporal_fields(global_object, item_object, field_names, Vector<StringView> { "timeZone"sv }));
  129. // g. Let timeZone be ! Get(fields, "timeZone").
  130. auto time_zone_value = MUST(fields->get(vm.names.timeZone));
  131. // h. Set timeZone to ? ToTemporalTimeZone(timeZone).
  132. time_zone = TRY(to_temporal_time_zone(global_object, time_zone_value));
  133. // i. Let offsetString be ! Get(fields, "offset").
  134. auto offset_string_value = MUST(fields->get(vm.names.offset));
  135. // j. If offsetString is undefined, then
  136. if (offset_string_value.is_undefined()) {
  137. // i. Set offsetBehaviour to wall.
  138. offset_behavior = OffsetBehavior::Wall;
  139. }
  140. // k. Else,
  141. else {
  142. // i. Set offsetString to ? ToString(offsetString).
  143. offset_string = TRY(offset_string_value.to_string(global_object));
  144. }
  145. // l. Let result be ? InterpretTemporalDateTimeFields(calendar, fields, options).
  146. result = TRY(interpret_temporal_date_time_fields(global_object, *calendar, *fields, *options));
  147. }
  148. // 6. Else,
  149. else {
  150. // a. Perform ? ToTemporalOverflow(options).
  151. (void)TRY(to_temporal_overflow(global_object, options));
  152. // b. Let string be ? ToString(item).
  153. auto string = TRY(item.to_string(global_object));
  154. // c. Let result be ? ParseTemporalZonedDateTimeString(string).
  155. auto parsed_result = TRY(parse_temporal_zoned_date_time_string(global_object, string));
  156. // NOTE: The ISODateTime struct inside parsed_result will be moved into `result` at the end of this path to avoid mismatching names.
  157. // Thus, all remaining references to `result` in this path actually refers to `parsed_result`.
  158. // d. Let timeZoneName be result.[[TimeZoneName]].
  159. auto time_zone_name = parsed_result.time_zone.name;
  160. // e. Assert: timeZoneName is not undefined.
  161. VERIFY(time_zone_name.has_value());
  162. // f. If ParseText(StringToCodePoints(timeZoneName), TimeZoneNumericUTCOffset) is a List of errors, then
  163. if (!is_valid_time_zone_numeric_utc_offset_syntax(*time_zone_name)) {
  164. // i. If IsValidTimeZoneName(timeZoneName) is false, throw a RangeError exception.
  165. if (!is_valid_time_zone_name(*time_zone_name))
  166. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidTimeZoneName, *time_zone_name);
  167. // ii. Set timeZoneName to ! CanonicalizeTimeZoneName(timeZoneName).
  168. time_zone_name = canonicalize_time_zone_name(*time_zone_name);
  169. }
  170. // g. Let offsetString be result.[[TimeZoneOffsetString]].
  171. offset_string = move(parsed_result.time_zone.offset_string);
  172. // h. If result.[[TimeZoneZ]] is true, then
  173. if (parsed_result.time_zone.z) {
  174. // i. Set offsetBehaviour to exact.
  175. offset_behavior = OffsetBehavior::Exact;
  176. }
  177. // i. Else if offsetString is undefined, then
  178. else if (!offset_string.has_value()) {
  179. // i. Set offsetBehaviour to wall.
  180. offset_behavior = OffsetBehavior::Wall;
  181. }
  182. // j. Let timeZone be ! CreateTemporalTimeZone(timeZoneName).
  183. time_zone = MUST(create_temporal_time_zone(global_object, *time_zone_name));
  184. // k. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  185. auto temporal_calendar_like = parsed_result.date_time.calendar.has_value()
  186. ? js_string(vm, parsed_result.date_time.calendar.value())
  187. : js_undefined();
  188. calendar = TRY(to_temporal_calendar_with_iso_default(global_object, temporal_calendar_like));
  189. // l. Set matchBehaviour to match minutes.
  190. match_behavior = MatchBehavior::MatchMinutes;
  191. // See NOTE above about why this is done.
  192. result = move(parsed_result.date_time);
  193. }
  194. // 7. Let offsetNanoseconds be 0.
  195. double offset_nanoseconds = 0;
  196. // 8. If offsetBehaviour is option, then
  197. if (offset_behavior == OffsetBehavior::Option) {
  198. // a. Set offsetNanoseconds to ? ParseTimeZoneOffsetString(offsetString).
  199. offset_nanoseconds = TRY(parse_time_zone_offset_string(global_object, *offset_string));
  200. }
  201. // 9. Let disambiguation be ? ToTemporalDisambiguation(options).
  202. auto disambiguation = TRY(to_temporal_disambiguation(global_object, options));
  203. // 10. Let offsetOption be ? ToTemporalOffset(options, "reject").
  204. auto offset_option = TRY(to_temporal_offset(global_object, options, "reject"));
  205. // 11. Let epochNanoseconds be ? InterpretISODateTimeOffset(result.[[Year]], result.[[Month]], result.[[Day]], result.[[Hour]], result.[[Minute]], result.[[Second]], result.[[Millisecond]], result.[[Microsecond]], result.[[Nanosecond]], offsetBehaviour, offsetNanoseconds, timeZone, disambiguation, offsetOption, matchBehaviour).
  206. auto* epoch_nanoseconds = TRY(interpret_iso_date_time_offset(global_object, result.year, result.month, result.day, result.hour, result.minute, result.second, result.millisecond, result.microsecond, result.nanosecond, offset_behavior, offset_nanoseconds, time_zone, disambiguation, offset_option, match_behavior));
  207. // 12. Return ! CreateTemporalZonedDateTime(epochNanoseconds, timeZone, calendar).
  208. return MUST(create_temporal_zoned_date_time(global_object, *epoch_nanoseconds, *time_zone, *calendar));
  209. }
  210. // 6.5.3 CreateTemporalZonedDateTime ( epochNanoseconds, timeZone, calendar [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporalzoneddatetime
  211. ThrowCompletionOr<ZonedDateTime*> create_temporal_zoned_date_time(GlobalObject& global_object, BigInt const& epoch_nanoseconds, Object& time_zone, Object& calendar, FunctionObject const* new_target)
  212. {
  213. // 1. Assert: ! IsValidEpochNanoseconds(epochNanoseconds) is true.
  214. VERIFY(is_valid_epoch_nanoseconds(epoch_nanoseconds));
  215. // 2. If newTarget is not present, set newTarget to %Temporal.ZonedDateTime%.
  216. if (!new_target)
  217. new_target = global_object.temporal_zoned_date_time_constructor();
  218. // 3. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.ZonedDateTime.prototype%", « [[InitializedTemporalZonedDateTime]], [[Nanoseconds]], [[TimeZone]], [[Calendar]] »).
  219. // 4. Set object.[[Nanoseconds]] to epochNanoseconds.
  220. // 5. Set object.[[TimeZone]] to timeZone.
  221. // 6. Set object.[[Calendar]] to calendar.
  222. auto* object = TRY(ordinary_create_from_constructor<ZonedDateTime>(global_object, *new_target, &GlobalObject::temporal_time_zone_prototype, epoch_nanoseconds, time_zone, calendar));
  223. // 7. Return object.
  224. return object;
  225. }
  226. // 6.5.4 TemporalZonedDateTimeToString ( zonedDateTime, precision, showCalendar, showTimeZone, showOffset [ , increment, unit, roundingMode ] ), https://tc39.es/proposal-temporal/#sec-temporal-temporalzoneddatetimetostring
  227. ThrowCompletionOr<String> temporal_zoned_date_time_to_string(GlobalObject& global_object, ZonedDateTime& zoned_date_time, Variant<StringView, u8> const& precision, StringView show_calendar, StringView show_time_zone, StringView show_offset, Optional<u64> increment, Optional<StringView> unit, Optional<StringView> rounding_mode)
  228. {
  229. // 1. If increment is not present, set increment to 1.
  230. if (!increment.has_value())
  231. increment = 1;
  232. // 2. If unit is not present, set unit to "nanosecond".
  233. if (!unit.has_value())
  234. unit = "nanosecond"sv;
  235. // 3. If roundingMode is not present, set roundingMode to "trunc".
  236. if (!rounding_mode.has_value())
  237. rounding_mode = "trunc"sv;
  238. // 4. Let ns be ! RoundTemporalInstant(zonedDateTime.[[Nanoseconds]], increment, unit, roundingMode).
  239. auto* ns = round_temporal_instant(global_object, zoned_date_time.nanoseconds(), *increment, *unit, *rounding_mode);
  240. // 5. Let timeZone be zonedDateTime.[[TimeZone]].
  241. auto& time_zone = zoned_date_time.time_zone();
  242. // 6. Let instant be ! CreateTemporalInstant(ns).
  243. auto* instant = MUST(create_temporal_instant(global_object, *ns));
  244. // 7. Let isoCalendar be ! GetISO8601Calendar().
  245. auto* iso_calendar = get_iso8601_calendar(global_object);
  246. // 8. Let temporalDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, instant, isoCalendar).
  247. auto* temporal_date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, &time_zone, *instant, *iso_calendar));
  248. // 9. Let dateTimeString be ? TemporalDateTimeToString(temporalDateTime.[[ISOYear]], temporalDateTime.[[ISOMonth]], temporalDateTime.[[ISODay]], temporalDateTime.[[ISOHour]], temporalDateTime.[[ISOMinute]], temporalDateTime.[[ISOSecond]], temporalDateTime.[[ISOMillisecond]], temporalDateTime.[[ISOMicrosecond]], temporalDateTime.[[ISONanosecond]], isoCalendar, precision, "never").
  249. auto date_time_string = TRY(temporal_date_time_to_string(global_object, temporal_date_time->iso_year(), temporal_date_time->iso_month(), temporal_date_time->iso_day(), temporal_date_time->iso_hour(), temporal_date_time->iso_minute(), temporal_date_time->iso_second(), temporal_date_time->iso_millisecond(), temporal_date_time->iso_microsecond(), temporal_date_time->iso_nanosecond(), iso_calendar, precision, "never"sv));
  250. String offset_string;
  251. // 10. If showOffset is "never", then
  252. if (show_offset == "never"sv) {
  253. // a. Let offsetString be the empty String.
  254. offset_string = String::empty();
  255. }
  256. // 11. Else,
  257. else {
  258. // a. Let offsetNs be ? GetOffsetNanosecondsFor(timeZone, instant).
  259. auto offset_ns = TRY(get_offset_nanoseconds_for(global_object, &time_zone, *instant));
  260. // b. Let offsetString be ! FormatISOTimeZoneOffsetString(offsetNs).
  261. offset_string = format_iso_time_zone_offset_string(offset_ns);
  262. }
  263. String time_zone_string;
  264. // 12. If showTimeZone is "never", then
  265. if (show_time_zone == "never"sv) {
  266. // a. Let timeZoneString be the empty String.
  267. time_zone_string = String::empty();
  268. }
  269. // 13. Else,
  270. else {
  271. // a. Let timeZoneID be ? ToString(timeZone).
  272. auto time_zone_id = TRY(Value(&time_zone).to_string(global_object));
  273. // b. Let timeZoneString be the string-concatenation of the code unit 0x005B (LEFT SQUARE BRACKET), timeZoneID, and the code unit 0x005D (RIGHT SQUARE BRACKET).
  274. time_zone_string = String::formatted("[{}]", time_zone_id);
  275. }
  276. // 14. Let calendarID be ? ToString(zonedDateTime.[[Calendar]]).
  277. auto calendar_id = TRY(Value(&zoned_date_time.calendar()).to_string(global_object));
  278. // 15. Let calendarString be ! FormatCalendarAnnotation(calendarID, showCalendar).
  279. auto calendar_string = format_calendar_annotation(calendar_id, show_calendar);
  280. // 16. Return the string-concatenation of dateTimeString, offsetString, timeZoneString, and calendarString.
  281. return String::formatted("{}{}{}{}", date_time_string, offset_string, time_zone_string, calendar_string);
  282. }
  283. // 6.5.5 AddZonedDateTime ( epochNanoseconds, timeZone, calendar, years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-addzoneddatetime
  284. ThrowCompletionOr<BigInt*> add_zoned_date_time(GlobalObject& global_object, BigInt const& epoch_nanoseconds, Value time_zone, Object& calendar, double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds, Object* options)
  285. {
  286. // 1. If options is not present, set options to undefined.
  287. // 2. Assert: Type(options) is Object or Undefined.
  288. // 3. If all of years, months, weeks, and days are 0, then
  289. if (years == 0 && months == 0 && weeks == 0 && days == 0) {
  290. // a. Return ? AddInstant(epochNanoseconds, hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
  291. return add_instant(global_object, epoch_nanoseconds, hours, minutes, seconds, milliseconds, microseconds, nanoseconds);
  292. }
  293. // 4. Let instant be ! CreateTemporalInstant(epochNanoseconds).
  294. auto* instant = MUST(create_temporal_instant(global_object, epoch_nanoseconds));
  295. // 5. Let temporalDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, instant, calendar).
  296. auto* temporal_date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, time_zone, *instant, calendar));
  297. // 6. Let datePart be ! CreateTemporalDate(temporalDateTime.[[ISOYear]], temporalDateTime.[[ISOMonth]], temporalDateTime.[[ISODay]], calendar).
  298. auto* date_part = MUST(create_temporal_date(global_object, temporal_date_time->iso_year(), temporal_date_time->iso_month(), temporal_date_time->iso_day(), calendar));
  299. // 7. Let dateDuration be ! CreateTemporalDuration(years, months, weeks, days, 0, 0, 0, 0, 0, 0).
  300. auto* date_duration = MUST(create_temporal_duration(global_object, years, months, weeks, days, 0, 0, 0, 0, 0, 0));
  301. // 8. Let addedDate be ? CalendarDateAdd(calendar, datePart, dateDuration, options).
  302. auto* added_date = TRY(calendar_date_add(global_object, calendar, date_part, *date_duration, options));
  303. // 9. Let intermediateDateTime be ? CreateTemporalDateTime(addedDate.[[ISOYear]], addedDate.[[ISOMonth]], addedDate.[[ISODay]], temporalDateTime.[[ISOHour]], temporalDateTime.[[ISOMinute]], temporalDateTime.[[ISOSecond]], temporalDateTime.[[ISOMillisecond]], temporalDateTime.[[ISOMicrosecond]], temporalDateTime.[[ISONanosecond]], calendar).
  304. auto* intermediate_date_time = TRY(create_temporal_date_time(global_object, added_date->iso_year(), added_date->iso_month(), added_date->iso_day(), temporal_date_time->iso_hour(), temporal_date_time->iso_minute(), temporal_date_time->iso_second(), temporal_date_time->iso_millisecond(), temporal_date_time->iso_microsecond(), temporal_date_time->iso_nanosecond(), calendar));
  305. // 10. Let intermediateInstant be ? BuiltinTimeZoneGetInstantFor(timeZone, intermediateDateTime, "compatible").
  306. auto* intermediate_instant = TRY(builtin_time_zone_get_instant_for(global_object, time_zone, *intermediate_date_time, "compatible"sv));
  307. // 11. Return ? AddInstant(intermediateInstant.[[Nanoseconds]], hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
  308. return add_instant(global_object, intermediate_instant->nanoseconds(), hours, minutes, seconds, milliseconds, microseconds, nanoseconds);
  309. }
  310. // 6.5.6 DifferenceZonedDateTime ( ns1, ns2, timeZone, calendar, largestUnit, options ), https://tc39.es/proposal-temporal/#sec-temporal-differencezoneddatetime
  311. ThrowCompletionOr<DurationRecord> difference_zoned_date_time(GlobalObject& global_object, BigInt const& nanoseconds1, BigInt const& nanoseconds2, Object& time_zone, Object& calendar, StringView largest_unit, Object const& options)
  312. {
  313. // 1. If ns1 is ns2, then
  314. if (nanoseconds1.big_integer() == nanoseconds2.big_integer()) {
  315. // a. Return ! CreateDurationRecord(0, 0, 0, 0, 0, 0, 0, 0, 0, 0).
  316. return create_duration_record(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  317. }
  318. // 2. Let startInstant be ! CreateTemporalInstant(ns1).
  319. auto* start_instant = MUST(create_temporal_instant(global_object, nanoseconds1));
  320. // 3. Let startDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, startInstant, calendar).
  321. auto* start_date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, &time_zone, *start_instant, calendar));
  322. // 4. Let endInstant be ! CreateTemporalInstant(ns2).
  323. auto* end_instant = MUST(create_temporal_instant(global_object, nanoseconds2));
  324. // 5. Let endDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, endInstant, calendar).
  325. auto* end_date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, &time_zone, *end_instant, calendar));
  326. // 6. Let dateDifference be ? DifferenceISODateTime(startDateTime.[[ISOYear]], startDateTime.[[ISOMonth]], startDateTime.[[ISODay]], startDateTime.[[ISOHour]], startDateTime.[[ISOMinute]], startDateTime.[[ISOSecond]], startDateTime.[[ISOMillisecond]], startDateTime.[[ISOMicrosecond]], startDateTime.[[ISONanosecond]], endDateTime.[[ISOYear]], endDateTime.[[ISOMonth]], endDateTime.[[ISODay]], endDateTime.[[ISOHour]], endDateTime.[[ISOMinute]], endDateTime.[[ISOSecond]], endDateTime.[[ISOMillisecond]], endDateTime.[[ISOMicrosecond]], endDateTime.[[ISONanosecond]], calendar, largestUnit, options).
  327. auto date_difference = TRY(difference_iso_date_time(global_object, start_date_time->iso_year(), start_date_time->iso_month(), start_date_time->iso_day(), start_date_time->iso_hour(), start_date_time->iso_minute(), start_date_time->iso_second(), start_date_time->iso_millisecond(), start_date_time->iso_microsecond(), start_date_time->iso_nanosecond(), end_date_time->iso_year(), end_date_time->iso_month(), end_date_time->iso_day(), end_date_time->iso_hour(), end_date_time->iso_minute(), end_date_time->iso_second(), end_date_time->iso_millisecond(), end_date_time->iso_microsecond(), end_date_time->iso_nanosecond(), calendar, largest_unit, options));
  328. // 7. Let intermediateNs be ? AddZonedDateTime(ns1, timeZone, calendar, dateDifference.[[Years]], dateDifference.[[Months]], dateDifference.[[Weeks]], 0, 0, 0, 0, 0, 0, 0).
  329. auto* intermediate_ns = TRY(add_zoned_date_time(global_object, nanoseconds1, &time_zone, calendar, date_difference.years, date_difference.months, date_difference.weeks, 0, 0, 0, 0, 0, 0, 0));
  330. // 8. Let timeRemainderNs be ns2 - intermediateNs.
  331. auto time_remainder_ns = nanoseconds2.big_integer().minus(intermediate_ns->big_integer());
  332. // 9. Let intermediate be ! CreateTemporalZonedDateTime(intermediateNs, timeZone, calendar).
  333. auto* intermediate = MUST(create_temporal_zoned_date_time(global_object, *intermediate_ns, time_zone, calendar));
  334. // 10. Let result be ? NanosecondsToDays(timeRemainderNs, intermediate).
  335. auto result = TRY(nanoseconds_to_days(global_object, time_remainder_ns, intermediate));
  336. // 11. Let timeDifference be ! BalanceDuration(0, 0, 0, 0, 0, 0, result.[[Nanoseconds]], "hour").
  337. auto time_difference = MUST(balance_duration(global_object, 0, 0, 0, 0, 0, 0, result.nanoseconds, "hour"sv));
  338. // 12. Return ! CreateDurationRecord(dateDifference.[[Years]], dateDifference.[[Months]], dateDifference.[[Weeks]], result.[[Days]], timeDifference.[[Hours]], timeDifference.[[Minutes]], timeDifference.[[Seconds]], timeDifference.[[Milliseconds]], timeDifference.[[Microseconds]], timeDifference.[[Nanoseconds]]).
  339. return create_duration_record(date_difference.years, date_difference.months, date_difference.weeks, result.days, time_difference.hours, time_difference.minutes, time_difference.seconds, time_difference.milliseconds, time_difference.microseconds, time_difference.nanoseconds);
  340. }
  341. // 6.5.7 NanosecondsToDays ( nanoseconds, relativeTo ), https://tc39.es/proposal-temporal/#sec-temporal-nanosecondstodays
  342. ThrowCompletionOr<NanosecondsToDaysResult> nanoseconds_to_days(GlobalObject& global_object, Crypto::SignedBigInteger nanoseconds, Value relative_to_value)
  343. {
  344. auto& vm = global_object.vm();
  345. // 1. Let dayLengthNs be nsPerDay.
  346. auto day_length_ns = ns_per_day_bigint;
  347. // 2. If nanoseconds = 0, then
  348. if (nanoseconds == "0"_bigint) {
  349. // a. Return the Record { [[Days]]: 0, [[Nanoseconds]]: 0, [[DayLength]]: dayLengthNs }.
  350. return NanosecondsToDaysResult { .days = 0, .nanoseconds = "0"_sbigint, .day_length = day_length_ns.to_double() };
  351. }
  352. // 3. If nanoseconds < 0, let sign be -1; else, let sign be 1.
  353. auto sign = nanoseconds.is_negative() ? -1 : 1;
  354. // 4. If Type(relativeTo) is not Object or relativeTo does not have an [[InitializedTemporalZonedDateTime]] internal slot, then
  355. if (!relative_to_value.is_object() || !is<ZonedDateTime>(relative_to_value.as_object())) {
  356. // a. Return the Record { [[Days]]: RoundTowardsZero(nanoseconds / dayLengthNs), [[Nanoseconds]]: (abs(nanoseconds) modulo dayLengthNs) × sign, [[DayLength]]: dayLengthNs }.
  357. return NanosecondsToDaysResult {
  358. .days = nanoseconds.divided_by(day_length_ns).quotient.to_double(),
  359. .nanoseconds = Crypto::SignedBigInteger { nanoseconds.unsigned_value() }.divided_by(day_length_ns).remainder.multiplied_by(Crypto::SignedBigInteger { (i32)sign }),
  360. .day_length = day_length_ns.to_double()
  361. };
  362. }
  363. auto& relative_to = static_cast<ZonedDateTime&>(relative_to_value.as_object());
  364. // 5. Let startNs be ℝ(relativeTo.[[Nanoseconds]]).
  365. auto& start_ns = relative_to.nanoseconds().big_integer();
  366. // 6. Let startInstant be ! CreateTemporalInstant(ℤ(startNs)).
  367. auto* start_instant = MUST(create_temporal_instant(global_object, *js_bigint(vm, start_ns)));
  368. // 7. Let startDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(relativeTo.[[TimeZone]], startInstant, relativeTo.[[Calendar]]).
  369. auto* start_date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, &relative_to.time_zone(), *start_instant, relative_to.calendar()));
  370. // 8. Let endNs be startNs + nanoseconds.
  371. auto end_ns = start_ns.plus(nanoseconds);
  372. auto* end_ns_bigint = js_bigint(vm, end_ns);
  373. // 9. If ! IsValidEpochNanoseconds(ℤ(endNs)) is false, throw a RangeError exception.
  374. if (!is_valid_epoch_nanoseconds(*end_ns_bigint))
  375. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidEpochNanoseconds);
  376. // 10. Let endInstant be ! CreateTemporalInstant(ℤ(endNs)).
  377. auto* end_instant = MUST(create_temporal_instant(global_object, *end_ns_bigint));
  378. // 11. Let endDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(relativeTo.[[TimeZone]], endInstant, relativeTo.[[Calendar]]).
  379. auto* end_date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, &relative_to.time_zone(), *end_instant, relative_to.calendar()));
  380. // 12. Let dateDifference be ? DifferenceISODateTime(startDateTime.[[ISOYear]], startDateTime.[[ISOMonth]], startDateTime.[[ISODay]], startDateTime.[[ISOHour]], startDateTime.[[ISOMinute]], startDateTime.[[ISOSecond]], startDateTime.[[ISOMillisecond]], startDateTime.[[ISOMicrosecond]], startDateTime.[[ISONanosecond]], endDateTime.[[ISOYear]], endDateTime.[[ISOMonth]], endDateTime.[[ISODay]], endDateTime.[[ISOHour]], endDateTime.[[ISOMinute]], endDateTime.[[ISOSecond]], endDateTime.[[ISOMillisecond]], endDateTime.[[ISOMicrosecond]], endDateTime.[[ISONanosecond]], relativeTo.[[Calendar]], "day", OrdinaryObjectCreate(null)).
  381. auto date_difference = TRY(difference_iso_date_time(global_object, start_date_time->iso_year(), start_date_time->iso_month(), start_date_time->iso_day(), start_date_time->iso_hour(), start_date_time->iso_minute(), start_date_time->iso_second(), start_date_time->iso_millisecond(), start_date_time->iso_microsecond(), start_date_time->iso_nanosecond(), end_date_time->iso_year(), end_date_time->iso_month(), end_date_time->iso_day(), end_date_time->iso_hour(), end_date_time->iso_minute(), end_date_time->iso_second(), end_date_time->iso_millisecond(), end_date_time->iso_microsecond(), end_date_time->iso_nanosecond(), relative_to.calendar(), "day"sv, *Object::create(global_object, nullptr)));
  382. // 13. Let days be dateDifference.[[Days]].
  383. auto days = date_difference.days;
  384. // 14. Let intermediateNs be ℝ(? AddZonedDateTime(ℤ(startNs), relativeTo.[[TimeZone]], relativeTo.[[Calendar]], 0, 0, 0, days, 0, 0, 0, 0, 0, 0)).
  385. auto intermediate_ns = TRY(add_zoned_date_time(global_object, *js_bigint(vm, start_ns), &relative_to.time_zone(), relative_to.calendar(), 0, 0, 0, days, 0, 0, 0, 0, 0, 0))->big_integer();
  386. // 15. If sign is 1, then
  387. if (sign == 1) {
  388. // a. Repeat, while days > 0 and intermediateNs > endNs,
  389. while (days > 0 && intermediate_ns > end_ns) {
  390. // i. Set days to days - 1.
  391. days--;
  392. // ii. Set intermediateNs to ℝ(? AddZonedDateTime(ℤ(startNs), relativeTo.[[TimeZone]], relativeTo.[[Calendar]], 0, 0, 0, days, 0, 0, 0, 0, 0, 0)).
  393. intermediate_ns = TRY(add_zoned_date_time(global_object, *js_bigint(vm, start_ns), &relative_to.time_zone(), relative_to.calendar(), 0, 0, 0, days, 0, 0, 0, 0, 0, 0))->big_integer();
  394. }
  395. }
  396. // 16. Set nanoseconds to endNs - intermediateNs.
  397. nanoseconds = end_ns.minus(intermediate_ns);
  398. // 17. Let done be false.
  399. // 18. Repeat, while done is false,
  400. while (true) {
  401. // a. Let oneDayFartherNs be ℝ(? AddZonedDateTime(ℤ(intermediateNs), relativeTo.[[TimeZone]], relativeTo.[[Calendar]], 0, 0, 0, sign, 0, 0, 0, 0, 0, 0)).
  402. auto one_day_farther_ns = TRY(add_zoned_date_time(global_object, *js_bigint(vm, intermediate_ns), &relative_to.time_zone(), relative_to.calendar(), 0, 0, 0, sign, 0, 0, 0, 0, 0, 0))->big_integer();
  403. // b. Set dayLengthNs to oneDayFartherNs - intermediateNs.
  404. day_length_ns = one_day_farther_ns.minus(intermediate_ns);
  405. // c. If (nanoseconds - dayLengthNs) × sign ≥ 0, then
  406. if (nanoseconds.minus(day_length_ns).multiplied_by(Crypto::SignedBigInteger { (i32)sign }) >= "0"_sbigint) {
  407. // i. Set nanoseconds to nanoseconds - dayLengthNs.
  408. nanoseconds = nanoseconds.minus(day_length_ns);
  409. // ii. Set intermediateNs to oneDayFartherNs.
  410. intermediate_ns = move(one_day_farther_ns);
  411. // iii. Set days to days + sign.
  412. days += sign;
  413. }
  414. // d. Else,
  415. else {
  416. // i. Set done to true.
  417. break;
  418. }
  419. }
  420. // 19. Return the Record { [[Days]]: days, [[Nanoseconds]]: nanoseconds, [[DayLength]]: abs(dayLengthNs) }.
  421. return NanosecondsToDaysResult { .days = days, .nanoseconds = move(nanoseconds), .day_length = fabs(day_length_ns.to_double()) };
  422. }
  423. // 6.5.8 DifferenceTemporalZonedDateTime ( operation, zonedDateTime, other, options ), https://tc39.es/proposal-temporal/#sec-temporal-differencetemporalzoneddatetime
  424. ThrowCompletionOr<Duration*> difference_temporal_zoned_date_time(GlobalObject& global_object, DifferenceOperation operation, ZonedDateTime& zoned_date_time, Value other_value, Value options_value)
  425. {
  426. auto& vm = global_object.vm();
  427. // 1. If operation is since, let sign be -1. Otherwise, let sign be 1.
  428. i8 sign = operation == DifferenceOperation::Since ? -1 : 1;
  429. // 2. Set other to ? ToTemporalZonedDateTime(other).
  430. auto* other = TRY(to_temporal_zoned_date_time(global_object, other_value));
  431. // 3. If ? CalendarEquals(zonedDateTime.[[Calendar]], other.[[Calendar]]) is false, then
  432. if (!TRY(calendar_equals(global_object, zoned_date_time.calendar(), other->calendar()))) {
  433. // a. Throw a RangeError exception.
  434. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalDifferentCalendars);
  435. }
  436. // 4. Set options to ? GetOptionsObject(options).
  437. auto const* options = TRY(get_options_object(global_object, options_value));
  438. // 5. Let smallestUnit be ? GetTemporalUnit(options, "smallestUnit", datetime, "nanosecond").
  439. auto smallest_unit = TRY(get_temporal_unit(global_object, *options, vm.names.smallestUnit, UnitGroup::DateTime, { "nanosecond"sv }));
  440. // 6. Let defaultLargestUnit be ! LargerOfTwoTemporalUnits("hour", smallestUnit).
  441. auto default_largest_unit = larger_of_two_temporal_units("hour"sv, *smallest_unit);
  442. // 7. Let largestUnit be ? GetTemporalUnit(options, "largestUnit", datetime, "auto").
  443. auto largest_unit = TRY(get_temporal_unit(global_object, *options, vm.names.largestUnit, UnitGroup::DateTime, { "auto"sv }));
  444. // 8. If largestUnit is "auto", set largestUnit to defaultLargestUnit.
  445. if (largest_unit == "auto"sv)
  446. largest_unit = default_largest_unit;
  447. // 9. If LargerOfTwoTemporalUnits(largestUnit, smallestUnit) is not largestUnit, throw a RangeError exception.
  448. if (larger_of_two_temporal_units(*largest_unit, *smallest_unit) != largest_unit)
  449. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidUnitRange, *smallest_unit, *largest_unit);
  450. // 10. Let roundingMode be ? ToTemporalRoundingMode(options, "trunc").
  451. auto rounding_mode = TRY(to_temporal_rounding_mode(global_object, *options, "trunc"sv));
  452. // 11. If operation is since, then
  453. if (operation == DifferenceOperation::Since) {
  454. // a. Set roundingMode to ! NegateTemporalRoundingMode(roundingMode).
  455. rounding_mode = negate_temporal_rounding_mode(rounding_mode);
  456. }
  457. // 12. Let maximum be ! MaximumTemporalDurationRoundingIncrement(smallestUnit).
  458. auto maximum = maximum_temporal_duration_rounding_increment(*smallest_unit);
  459. // 13. Let roundingIncrement be ? ToTemporalRoundingIncrement(options, maximum, false).
  460. auto rounding_increment = TRY(to_temporal_rounding_increment(global_object, *options, Optional<double>(maximum), false));
  461. // 14. If largestUnit is not one of "year", "month", "week", or "day", then
  462. if (!largest_unit->is_one_of("year"sv, "month"sv, "week"sv, "day"sv)) {
  463. // a. Let differenceNs be ! DifferenceInstant(zonedDateTime.[[Nanoseconds]], other.[[Nanoseconds]], roundingIncrement, smallestUnit, roundingMode).
  464. auto* difference_ns = difference_instant(global_object, zoned_date_time.nanoseconds(), other->nanoseconds(), rounding_increment, *smallest_unit, rounding_mode);
  465. // b. Assert: The following steps cannot fail due to overflow in the Number domain because abs(differenceNs) ≤ 2 × nsMaxInstant.
  466. // c. Let balanceResult be ! BalanceDuration(0, 0, 0, 0, 0, 0, differenceNs, largestUnit).
  467. auto balance_result = MUST(balance_duration(global_object, 0, 0, 0, 0, 0, 0, difference_ns->big_integer(), *largest_unit));
  468. // d. Return ! CreateTemporalDuration(0, 0, 0, 0, sign × balanceResult.[[Hours]], sign × balanceResult.[[Minutes]], sign × balanceResult.[[Seconds]], sign × balanceResult.[[Milliseconds]], sign × balanceResult.[[Microseconds]], sign × balanceResult.[[Nanoseconds]]).
  469. return MUST(create_temporal_duration(global_object, 0, 0, 0, 0, sign * balance_result.hours, sign * balance_result.minutes, sign * balance_result.seconds, sign * balance_result.milliseconds, sign * balance_result.microseconds, sign * balance_result.nanoseconds));
  470. }
  471. // 15. If ? TimeZoneEquals(zonedDateTime.[[TimeZone]], other.[[TimeZone]]) is false, then
  472. if (!TRY(time_zone_equals(global_object, zoned_date_time.time_zone(), other->time_zone()))) {
  473. // a. Throw a RangeError exception.
  474. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalDifferentTimeZones);
  475. }
  476. // 16. Let untilOptions be ? MergeLargestUnitOption(options, largestUnit).
  477. auto* until_options = TRY(merge_largest_unit_option(global_object, *options, *largest_unit));
  478. // 17. Let difference be ? DifferenceZonedDateTime(zonedDateTime.[[Nanoseconds]], other.[[Nanoseconds]], zonedDateTime.[[TimeZone]], zonedDateTime.[[Calendar]], largestUnit, untilOptions).
  479. auto difference = TRY(difference_zoned_date_time(global_object, zoned_date_time.nanoseconds(), other->nanoseconds(), zoned_date_time.time_zone(), zoned_date_time.calendar(), *largest_unit, *until_options));
  480. // 18. Let roundResult be (? RoundDuration(difference.[[Years]], difference.[[Months]], difference.[[Weeks]], difference.[[Days]], difference.[[Hours]], difference.[[Minutes]], difference.[[Seconds]], difference.[[Milliseconds]], difference.[[Microseconds]], difference.[[Nanoseconds]], roundingIncrement, smallestUnit, roundingMode, zonedDateTime)).[[DurationRecord]].
  481. auto round_result = TRY(round_duration(global_object, difference.years, difference.months, difference.weeks, difference.days, difference.hours, difference.minutes, difference.seconds, difference.milliseconds, difference.microseconds, difference.nanoseconds, rounding_increment, *smallest_unit, rounding_mode, &zoned_date_time)).duration_record;
  482. // 19. Let result be ? AdjustRoundedDurationDays(roundResult.[[Years]], roundResult.[[Months]], roundResult.[[Weeks]], roundResult.[[Days]], roundResult.[[Hours]], roundResult.[[Minutes]], roundResult.[[Seconds]], roundResult.[[Milliseconds]], roundResult.[[Microseconds]], roundResult.[[Nanoseconds]], roundingIncrement, smallestUnit, roundingMode, zonedDateTime).
  483. auto result = TRY(adjust_rounded_duration_days(global_object, round_result.years, round_result.months, round_result.weeks, round_result.days, round_result.hours, round_result.minutes, round_result.seconds, round_result.milliseconds, round_result.microseconds, round_result.nanoseconds, rounding_increment, *smallest_unit, rounding_mode, &zoned_date_time));
  484. // 20. Return ! CreateTemporalDuration(sign × result.[[Years]], sign × result.[[Months]], sign × result.[[Weeks]], sign × result.[[Days]], sign × result.[[Hours]], sign × result.[[Minutes]], sign × result.[[Seconds]], sign × result.[[Milliseconds]], sign × result.[[Microseconds]], sign × result.[[Nanoseconds]]).
  485. return MUST(create_temporal_duration(global_object, sign * result.years, sign * result.months, sign * result.weeks, sign * result.days, sign * result.hours, sign * result.minutes, sign * result.seconds, sign * result.milliseconds, sign * result.microseconds, sign * result.nanoseconds));
  486. }
  487. // 6.5.9 AddDurationToOrSubtractDurationFromZonedDateTime ( operation, zonedDateTime, temporalDurationLike, options ), https://tc39.es/proposal-temporal/#sec-temporal-adddurationtoOrsubtractdurationfromzoneddatetime
  488. ThrowCompletionOr<ZonedDateTime*> add_duration_to_or_subtract_duration_from_zoned_date_time(GlobalObject& global_object, ArithmeticOperation operation, ZonedDateTime& zoned_date_time, Value temporal_duration_like, Value options_value)
  489. {
  490. // 1. If operation is subtract, let sign be -1. Otherwise, let sign be 1.
  491. i8 sign = operation == ArithmeticOperation::Subtract ? -1 : 1;
  492. // 2. Let duration be ? ToTemporalDurationRecord(temporalDurationLike).
  493. auto duration = TRY(to_temporal_duration_record(global_object, temporal_duration_like));
  494. // 3. Set options to ? GetOptionsObject(options).
  495. auto* options = TRY(get_options_object(global_object, options_value));
  496. // 4. Let timeZone be zonedDateTime.[[TimeZone]].
  497. auto& time_zone = zoned_date_time.time_zone();
  498. // 5. Let calendar be zonedDateTime.[[Calendar]].
  499. auto& calendar = zoned_date_time.calendar();
  500. // 6. Let epochNanoseconds be ? AddZonedDateTime(zonedDateTime.[[Nanoseconds]], timeZone, calendar, sign × duration.[[Years]], sign × duration.[[Months]], sign × duration.[[Weeks]], sign × duration.[[Days]], sign × duration.[[Hours]], sign × duration.[[Minutes]], sign × duration.[[Seconds]], sign × duration.[[Milliseconds]], sign × duration.[[Microseconds]], sign × duration.[[Nanoseconds]], options).
  501. auto* epoch_nanoseconds = TRY(add_zoned_date_time(global_object, zoned_date_time.nanoseconds(), &time_zone, calendar, sign * duration.years, sign * duration.months, sign * duration.weeks, sign * duration.days, sign * duration.hours, sign * duration.minutes, sign * duration.seconds, sign * duration.milliseconds, sign * duration.microseconds, sign * duration.nanoseconds, options));
  502. // 7. Return ! CreateTemporalZonedDateTime(epochNanoseconds, timeZone, calendar).
  503. return MUST(create_temporal_zoned_date_time(global_object, *epoch_nanoseconds, time_zone, calendar));
  504. }
  505. }