ZonedDateTime.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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/GlobalObject.h>
  9. #include <LibJS/Runtime/Temporal/Calendar.h>
  10. #include <LibJS/Runtime/Temporal/Duration.h>
  11. #include <LibJS/Runtime/Temporal/Instant.h>
  12. #include <LibJS/Runtime/Temporal/PlainDate.h>
  13. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  14. #include <LibJS/Runtime/Temporal/TimeZone.h>
  15. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  16. #include <LibJS/Runtime/Temporal/ZonedDateTimeConstructor.h>
  17. namespace JS::Temporal {
  18. // 6 Temporal.ZonedDateTime Objects, https://tc39.es/proposal-temporal/#sec-temporal-zoneddatetime-objects
  19. ZonedDateTime::ZonedDateTime(BigInt const& nanoseconds, Object& time_zone, Object& calendar, Object& prototype)
  20. : Object(prototype)
  21. , m_nanoseconds(nanoseconds)
  22. , m_time_zone(time_zone)
  23. , m_calendar(calendar)
  24. {
  25. }
  26. void ZonedDateTime::visit_edges(Cell::Visitor& visitor)
  27. {
  28. Base::visit_edges(visitor);
  29. visitor.visit(&m_nanoseconds);
  30. visitor.visit(&m_time_zone);
  31. visitor.visit(&m_calendar);
  32. }
  33. // 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
  34. 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)
  35. {
  36. auto& vm = global_object.vm();
  37. // 1. Assert: offsetNanoseconds is an integer.
  38. VERIFY(trunc(offset_nanoseconds) == offset_nanoseconds);
  39. // 2. Let calendar be ! GetISO8601Calendar().
  40. auto* calendar = get_iso8601_calendar(global_object);
  41. // 3. Let dateTime be ? CreateTemporalDateTime(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, calendar).
  42. auto* date_time = TRY(create_temporal_date_time(global_object, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond, *calendar));
  43. // 4. If offsetBehaviour is wall, or offsetOption is "ignore", then
  44. if (offset_behavior == OffsetBehavior::Wall || offset_option == "ignore"sv) {
  45. // a. Let instant be ? BuiltinTimeZoneGetInstantFor(timeZone, dateTime, disambiguation).
  46. auto* instant = TRY(builtin_time_zone_get_instant_for(global_object, time_zone, *date_time, disambiguation));
  47. // b. Return instant.[[Nanoseconds]].
  48. return &instant->nanoseconds();
  49. }
  50. // 5. If offsetBehaviour is exact, or offsetOption is "use", then
  51. if (offset_behavior == OffsetBehavior::Exact || offset_option == "use"sv) {
  52. // a. Let epochNanoseconds be ! GetEpochFromISOParts(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond).
  53. auto* epoch_nanoseconds = get_epoch_from_iso_parts(global_object, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond);
  54. // b. Return epochNanoseconds − offsetNanoseconds.
  55. auto offset_nanoseconds_bigint = Crypto::SignedBigInteger::create_from((i64)offset_nanoseconds);
  56. return js_bigint(vm, epoch_nanoseconds->big_integer().minus(offset_nanoseconds_bigint));
  57. }
  58. // 6. Assert: offsetBehaviour is option.
  59. VERIFY(offset_behavior == OffsetBehavior::Option);
  60. // 7. Assert: offsetOption is "prefer" or "reject".
  61. VERIFY(offset_option.is_one_of("prefer"sv, "reject"sv));
  62. // 8. Let possibleInstants be ? GetPossibleInstantsFor(timeZone, dateTime).
  63. auto possible_instants = TRY(get_possible_instants_for(global_object, time_zone, *date_time));
  64. // 9. For each element candidate of possibleInstants, do
  65. for (auto* candidate : possible_instants) {
  66. // a. Let candidateNanoseconds be ? GetOffsetNanosecondsFor(timeZone, candidate).
  67. auto candidate_nanoseconds = TRY(get_offset_nanoseconds_for(global_object, time_zone, *candidate));
  68. // b. If candidateNanoseconds = offsetNanoseconds, then
  69. if (candidate_nanoseconds == offset_nanoseconds) {
  70. // i. Return candidate.[[Nanoseconds]].
  71. return &candidate->nanoseconds();
  72. }
  73. // c. If matchBehaviour is match minutes, then
  74. if (match_behavior == MatchBehavior::MatchMinutes) {
  75. // i. Let roundedCandidateNanoseconds be ! RoundNumberToIncrement(candidateNanoseconds, 60 × 10^9, "halfExpand").
  76. auto rounded_candidate_nanoseconds = round_number_to_increment(candidate_nanoseconds, 60000000000, "halfExpand"sv);
  77. // ii. If roundedCandidateNanoseconds = offsetNanoseconds, then
  78. if (rounded_candidate_nanoseconds == offset_nanoseconds) {
  79. // 1. Return candidate.[[Nanoseconds]].
  80. return &candidate->nanoseconds();
  81. }
  82. }
  83. }
  84. // 10. If offsetOption is "reject", throw a RangeError exception.
  85. if (offset_option == "reject"sv)
  86. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidZonedDateTimeOffset);
  87. // 11. Let instant be ? DisambiguatePossibleInstants(possibleInstants, timeZone, dateTime, disambiguation).
  88. auto* instant = TRY(disambiguate_possible_instants(global_object, possible_instants, time_zone, *date_time, disambiguation));
  89. // 12. Return instant.[[Nanoseconds]].
  90. return &instant->nanoseconds();
  91. }
  92. // 6.5.2 ToTemporalZonedDateTime ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporalzoneddatetime
  93. ThrowCompletionOr<ZonedDateTime*> to_temporal_zoned_date_time(GlobalObject& global_object, Value item, Object* options)
  94. {
  95. auto& vm = global_object.vm();
  96. // 1. If options is not present, set options to OrdinaryObjectCreate(null).
  97. if (!options)
  98. options = Object::create(global_object, nullptr);
  99. // 2. Let offsetBehaviour be option.
  100. auto offset_behavior = OffsetBehavior::Option;
  101. // 3. Let matchBehaviour be match exactly.
  102. auto match_behavior = MatchBehavior::MatchExactly;
  103. Object* calendar = nullptr;
  104. Object* time_zone = nullptr;
  105. Optional<String> offset_string;
  106. ISODateTime result;
  107. // 4. If Type(item) is Object, then
  108. if (item.is_object()) {
  109. auto& item_object = item.as_object();
  110. // a. If item has an [[InitializedTemporalZonedDateTime]] internal slot, then
  111. if (is<ZonedDateTime>(item_object)) {
  112. // i. Return item.
  113. return &static_cast<ZonedDateTime&>(item_object);
  114. }
  115. // b. Let calendar be ? GetTemporalCalendarWithISODefault(item).
  116. calendar = TRY(get_temporal_calendar_with_iso_default(global_object, item_object));
  117. // c. Let fieldNames be ? CalendarFields(calendar, « "day", "hour", "microsecond", "millisecond", "minute", "month", "monthCode", "nanosecond", "second", "year" »).
  118. 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 }));
  119. // d. Append "timeZone" to fieldNames.
  120. field_names.append("timeZone");
  121. // e. Append "offset" to fieldNames.
  122. field_names.append("offset");
  123. // f. Let fields be ? PrepareTemporalFields(item, fieldNames, « "timeZone" »).
  124. auto* fields = TRY(prepare_temporal_fields(global_object, item_object, field_names, { "timeZone"sv }));
  125. // g. Let timeZone be ? Get(fields, "timeZone").
  126. auto time_zone_value = TRY(fields->get(vm.names.timeZone));
  127. // h. Set timeZone to ? ToTemporalTimeZone(timeZone).
  128. time_zone = TRY(to_temporal_time_zone(global_object, time_zone_value));
  129. // i. Let offsetString be ? Get(fields, "offset").
  130. auto offset_string_value = TRY(fields->get(vm.names.offset));
  131. // j. If offsetString is undefined, then
  132. if (offset_string_value.is_undefined()) {
  133. // i. Set offsetBehaviour to wall.
  134. offset_behavior = OffsetBehavior::Wall;
  135. }
  136. // k. Else,
  137. else {
  138. // i. Set offsetString to ? ToString(offsetString).
  139. offset_string = TRY(offset_string_value.to_string(global_object));
  140. }
  141. // l. Let result be ? InterpretTemporalDateTimeFields(calendar, fields, options).
  142. result = TRY(interpret_temporal_date_time_fields(global_object, *calendar, *fields, *options));
  143. }
  144. // 5. Else,
  145. else {
  146. // a. Perform ? ToTemporalOverflow(options).
  147. (void)TRY(to_temporal_overflow(global_object, *options));
  148. // b. Let string be ? ToString(item).
  149. auto string = TRY(item.to_string(global_object));
  150. // c. Let result be ? ParseTemporalZonedDateTimeString(string).
  151. auto parsed_result = TRY(parse_temporal_zoned_date_time_string(global_object, string));
  152. // NOTE: The ISODateTime struct inside parsed_result will be moved into `result` at the end of this path to avoid mismatching names.
  153. // Thus, all remaining references to `result` in this path actually refers to `parsed_result`.
  154. // d. Let timeZoneName be result.[[TimeZoneName]].
  155. auto time_zone_name = parsed_result.time_zone.name;
  156. // e. Assert: timeZoneName is not undefined.
  157. VERIFY(time_zone_name.has_value());
  158. // f. If ParseText(StringToCodePoints(timeZoneName), TimeZoneNumericUTCOffset) is a List of errors, then
  159. if (!is_valid_time_zone_numeric_utc_offset_syntax(*time_zone_name)) {
  160. // i. If ! IsValidTimeZoneName(timeZoneName) is false, throw a RangeError exception.
  161. if (!is_valid_time_zone_name(*time_zone_name))
  162. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidTimeZoneName, *time_zone_name);
  163. // ii. Set timeZoneName to ! CanonicalizeTimeZoneName(timeZoneName).
  164. time_zone_name = canonicalize_time_zone_name(*time_zone_name);
  165. }
  166. // g. Let offsetString be result.[[TimeZoneOffsetString]].
  167. offset_string = move(parsed_result.time_zone.offset_string);
  168. // h. If result.[[TimeZoneZ]] is true, then
  169. if (parsed_result.time_zone.z) {
  170. // i. Set offsetBehaviour to exact.
  171. offset_behavior = OffsetBehavior::Exact;
  172. }
  173. // i. Else if offsetString is undefined, then
  174. else if (!offset_string.has_value()) {
  175. // i. Set offsetBehaviour to wall.
  176. offset_behavior = OffsetBehavior::Wall;
  177. }
  178. // j. Let timeZone be ! CreateTemporalTimeZone(timeZoneName).
  179. time_zone = MUST(create_temporal_time_zone(global_object, *time_zone_name));
  180. // k. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  181. auto temporal_calendar_like = parsed_result.date_time.calendar.has_value()
  182. ? js_string(vm, parsed_result.date_time.calendar.value())
  183. : js_undefined();
  184. calendar = TRY(to_temporal_calendar_with_iso_default(global_object, temporal_calendar_like));
  185. // l. Set matchBehaviour to match minutes.
  186. match_behavior = MatchBehavior::MatchMinutes;
  187. // See NOTE above about why this is done.
  188. result = move(parsed_result.date_time);
  189. }
  190. // 6. Let offsetNanoseconds be 0.
  191. double offset_nanoseconds = 0;
  192. // 7. If offsetBehaviour is option, then
  193. if (offset_behavior == OffsetBehavior::Option) {
  194. // a. Set offsetNanoseconds to ? ParseTimeZoneOffsetString(offsetString).
  195. offset_nanoseconds = TRY(parse_time_zone_offset_string(global_object, *offset_string));
  196. }
  197. // 8. Let disambiguation be ? ToTemporalDisambiguation(options).
  198. auto disambiguation = TRY(to_temporal_disambiguation(global_object, *options));
  199. // 9. Let offsetOption be ? ToTemporalOffset(options, "reject").
  200. auto offset_option = TRY(to_temporal_offset(global_object, *options, "reject"));
  201. // 10. 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).
  202. 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));
  203. // 11. Return ! CreateTemporalZonedDateTime(epochNanoseconds, timeZone, calendar).
  204. return MUST(create_temporal_zoned_date_time(global_object, *epoch_nanoseconds, *time_zone, *calendar));
  205. }
  206. // 6.5.3 CreateTemporalZonedDateTime ( epochNanoseconds, timeZone, calendar [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporalzoneddatetime
  207. ThrowCompletionOr<ZonedDateTime*> create_temporal_zoned_date_time(GlobalObject& global_object, BigInt const& epoch_nanoseconds, Object& time_zone, Object& calendar, FunctionObject const* new_target)
  208. {
  209. // 1. Assert: Type(epochNanoseconds) is BigInt.
  210. // 3. Assert: Type(timeZone) is Object.
  211. // 4. Assert: Type(calendar) is Object.
  212. // 2. Assert: ! IsValidEpochNanoseconds(epochNanoseconds) is true.
  213. VERIFY(is_valid_epoch_nanoseconds(epoch_nanoseconds));
  214. // 5. If newTarget is not present, set newTarget to %Temporal.ZonedDateTime%.
  215. if (!new_target)
  216. new_target = global_object.temporal_zoned_date_time_constructor();
  217. // 6. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.ZonedDateTime.prototype%", « [[InitializedTemporalZonedDateTime]], [[Nanoseconds]], [[TimeZone]], [[Calendar]] »).
  218. // 7. Set object.[[Nanoseconds]] to epochNanoseconds.
  219. // 8. Set object.[[TimeZone]] to timeZone.
  220. // 9. Set object.[[Calendar]] to calendar.
  221. auto* object = TRY(ordinary_create_from_constructor<ZonedDateTime>(global_object, *new_target, &GlobalObject::temporal_time_zone_prototype, epoch_nanoseconds, time_zone, calendar));
  222. // 10. Return object.
  223. return object;
  224. }
  225. // 6.5.4 TemporalZonedDateTimeToString ( zonedDateTime, precision, showCalendar, showTimeZone, showOffset [ , increment, unit, roundingMode ] ), https://tc39.es/proposal-temporal/#sec-temporal-temporalzoneddatetimetostring
  226. 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)
  227. {
  228. // 1. Assert: Type(zonedDateTime) is Object and zonedDateTime has an [[InitializedTemporalZonedDateTime]] internal slot.
  229. // 2. If increment is not present, set increment to 1.
  230. if (!increment.has_value())
  231. increment = 1;
  232. // 3. If unit is not present, set unit to "nanosecond".
  233. if (!unit.has_value())
  234. unit = "nanosecond"sv;
  235. // 4. If roundingMode is not present, set roundingMode to "trunc".
  236. if (!rounding_mode.has_value())
  237. rounding_mode = "trunc"sv;
  238. // 5. 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. // 6. Let timeZone be zonedDateTime.[[TimeZone]].
  241. auto& time_zone = zoned_date_time.time_zone();
  242. // 7. Let instant be ! CreateTemporalInstant(ns).
  243. auto* instant = MUST(create_temporal_instant(global_object, *ns));
  244. // 8. Let isoCalendar be ! GetISO8601Calendar().
  245. auto* iso_calendar = get_iso8601_calendar(global_object);
  246. // 9. 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. // 10. 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. // 11. 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. // 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. // 13. 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. // 14. 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. // 15. Let calendarID be ? ToString(zonedDateTime.[[Calendar]]).
  277. auto calendar_id = TRY(Value(&zoned_date_time.calendar()).to_string(global_object));
  278. // 16. Let calendarString be ! FormatCalendarAnnotation(calendarID, showCalendar).
  279. auto calendar_string = format_calendar_annotation(calendar_id, show_calendar);
  280. // 17. 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 OrdinaryObjectCreate(null).
  287. if (!options)
  288. options = Object::create(global_object, nullptr);
  289. // 2. If all of years, months, weeks, and days are 0, then
  290. if (years == 0 && months == 0 && weeks == 0 && days == 0) {
  291. // a. Return ! AddInstant(epochNanoseconds, hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
  292. return MUST(add_instant(global_object, epoch_nanoseconds, hours, minutes, seconds, milliseconds, microseconds, nanoseconds));
  293. }
  294. // 3. Let instant be ! CreateTemporalInstant(epochNanoseconds).
  295. auto* instant = MUST(create_temporal_instant(global_object, epoch_nanoseconds));
  296. // 4. Let temporalDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, instant, calendar).
  297. auto* temporal_date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, time_zone, *instant, calendar));
  298. // 5. Let datePart be ? CreateTemporalDate(temporalDateTime.[[ISOYear]], temporalDateTime.[[ISOMonth]], temporalDateTime.[[ISODay]], calendar).
  299. auto* date_part = TRY(create_temporal_date(global_object, temporal_date_time->iso_year(), temporal_date_time->iso_month(), temporal_date_time->iso_day(), calendar));
  300. // 6. Let dateDuration be ! CreateTemporalDuration(years, months, weeks, days, 0, 0, 0, 0, 0, 0).
  301. auto* date_duration = MUST(create_temporal_duration(global_object, years, months, weeks, days, 0, 0, 0, 0, 0, 0));
  302. // 7. Let addedDate be ? CalendarDateAdd(calendar, datePart, dateDuration, options).
  303. auto* added_date = TRY(calendar_date_add(global_object, calendar, date_part, *date_duration, options));
  304. // 8. Let intermediateDateTime be ? CreateTemporalDateTime(addedDate.[[ISOYear]], addedDate.[[ISOMonth]], addedDate.[[ISODay]], temporalDateTime.[[ISOHour]], temporalDateTime.[[ISOMinute]], temporalDateTime.[[ISOSecond]], temporalDateTime.[[ISOMillisecond]], temporalDateTime.[[ISOMicrosecond]], temporalDateTime.[[ISONanosecond]], calendar).
  305. 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));
  306. // 9. Let intermediateInstant be ? BuiltinTimeZoneGetInstantFor(timeZone, intermediateDateTime, "compatible").
  307. auto* intermediate_instant = TRY(builtin_time_zone_get_instant_for(global_object, time_zone, *intermediate_date_time, "compatible"sv));
  308. // 10. Return ! AddInstant(intermediateInstant.[[Nanoseconds]], hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
  309. return MUST(add_instant(global_object, intermediate_instant->nanoseconds(), hours, minutes, seconds, milliseconds, microseconds, nanoseconds));
  310. }
  311. // 6.5.6 DifferenceZonedDateTime ( ns1, ns2, timeZone, calendar, largestUnit [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-differencezoneddatetime
  312. ThrowCompletionOr<DurationRecord> difference_zoned_date_time(GlobalObject& global_object, BigInt const& nanoseconds1, BigInt const& nanoseconds2, Object& time_zone, Object& calendar, StringView largest_unit, Object* options)
  313. {
  314. auto& vm = global_object.vm();
  315. // 1. Assert: Type(ns1) is BigInt.
  316. // 2. Assert: Type(ns2) is BigInt.
  317. // 3. If ns1 is ns2, then
  318. if (nanoseconds1.big_integer() == nanoseconds2.big_integer()) {
  319. // a. Return ! CreateDurationRecord(0, 0, 0, 0, 0, 0, 0, 0, 0, 0).
  320. return create_duration_record(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  321. }
  322. // 4. Let startInstant be ! CreateTemporalInstant(ns1).
  323. auto* start_instant = MUST(create_temporal_instant(global_object, nanoseconds1));
  324. // 5. Let startDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, startInstant, calendar).
  325. auto* start_date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, &time_zone, *start_instant, calendar));
  326. // 6. Let endInstant be ! CreateTemporalInstant(ns2).
  327. auto* end_instant = MUST(create_temporal_instant(global_object, nanoseconds2));
  328. // 7. Let endDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(timeZone, endInstant, calendar).
  329. auto* end_date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, &time_zone, *end_instant, calendar));
  330. // 8. 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).
  331. 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));
  332. // 9. Let intermediateNs be ? AddZonedDateTime(ns1, timeZone, calendar, dateDifference.[[Years]], dateDifference.[[Months]], dateDifference.[[Weeks]], 0, 0, 0, 0, 0, 0, 0).
  333. 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));
  334. // 10. Let timeRemainderNs be ns2 − intermediateNs.
  335. auto time_remainder_ns = nanoseconds2.big_integer().minus(intermediate_ns->big_integer());
  336. // 11. Let intermediate be ! CreateTemporalZonedDateTime(intermediateNs, timeZone, calendar).
  337. auto* intermediate = MUST(create_temporal_zoned_date_time(global_object, *intermediate_ns, time_zone, calendar));
  338. // 12. Let result be ? NanosecondsToDays(timeRemainderNs, intermediate).
  339. auto result = TRY(nanoseconds_to_days(global_object, *js_bigint(vm, time_remainder_ns), intermediate));
  340. // 13. Let timeDifference be ! BalanceDuration(0, 0, 0, 0, 0, 0, result.[[Nanoseconds]], "hour").
  341. auto time_difference = MUST(balance_duration(global_object, 0, 0, 0, 0, 0, 0, result.nanoseconds, "hour"sv));
  342. // 14. Return ! CreateDurationRecord(dateDifference.[[Years]], dateDifference.[[Months]], dateDifference.[[Weeks]], result.[[Days]], timeDifference.[[Hours]], timeDifference.[[Minutes]], timeDifference.[[Seconds]], timeDifference.[[Milliseconds]], timeDifference.[[Microseconds]], timeDifference.[[Nanoseconds]]).
  343. 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);
  344. }
  345. // 6.5.7 NanosecondsToDays ( nanoseconds, relativeTo ), https://tc39.es/proposal-temporal/#sec-temporal-nanosecondstodays
  346. ThrowCompletionOr<NanosecondsToDaysResult> nanoseconds_to_days(GlobalObject& global_object, BigInt const& nanoseconds_bigint, Value relative_to_value)
  347. {
  348. auto& vm = global_object.vm();
  349. // 1. Assert: Type(nanoseconds) is BigInt.
  350. // 2. Set nanoseconds to ℝ(nanoseconds).
  351. auto nanoseconds = nanoseconds_bigint.big_integer();
  352. // 3. Let dayLengthNs be 8.64 × 10^13.
  353. auto day_length_ns = "86400000000000"_sbigint;
  354. // 4. If nanoseconds = 0, then
  355. if (nanoseconds == "0"_bigint) {
  356. // a. Return the Record { [[Days]]: 0, [[Nanoseconds]]: 0, [[DayLength]]: dayLengthNs }.
  357. return NanosecondsToDaysResult { .days = 0, .nanoseconds = "0"_sbigint, .day_length = day_length_ns.to_double() };
  358. }
  359. // 5. If nanoseconds < 0, let sign be −1; else, let sign be 1.
  360. auto sign = nanoseconds.is_negative() ? -1 : 1;
  361. // 6. If Type(relativeTo) is not Object or relativeTo does not have an [[InitializedTemporalZonedDateTime]] internal slot, then
  362. if (!relative_to_value.is_object() || !is<ZonedDateTime>(relative_to_value.as_object())) {
  363. // a. Return the Record { [[Days]]: the integral part of nanoseconds / dayLengthNs, [[Nanoseconds]]: (abs(nanoseconds) modulo dayLengthNs) × sign, [[DayLength]]: dayLengthNs }.
  364. return NanosecondsToDaysResult {
  365. .days = nanoseconds.divided_by(day_length_ns).quotient.to_double(),
  366. .nanoseconds = Crypto::SignedBigInteger { nanoseconds.unsigned_value() }.divided_by(day_length_ns).remainder.multiplied_by(Crypto::SignedBigInteger { (i32)sign }),
  367. .day_length = day_length_ns.to_double()
  368. };
  369. }
  370. auto& relative_to = static_cast<ZonedDateTime&>(relative_to_value.as_object());
  371. // 7. Let startNs be ℝ(relativeTo.[[Nanoseconds]]).
  372. auto& start_ns = relative_to.nanoseconds().big_integer();
  373. // 8. Let startInstant be ! CreateTemporalInstant(ℤ(startNs)).
  374. auto* start_instant = MUST(create_temporal_instant(global_object, *js_bigint(vm, start_ns)));
  375. // 9. Let startDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(relativeTo.[[TimeZone]], startInstant, relativeTo.[[Calendar]]).
  376. auto* start_date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, &relative_to.time_zone(), *start_instant, relative_to.calendar()));
  377. // 10. Let endNs be startNs + nanoseconds.
  378. auto end_ns = start_ns.plus(nanoseconds);
  379. // 11. Let endInstant be ! CreateTemporalInstant(ℤ(endNs)).
  380. auto* end_instant = MUST(create_temporal_instant(global_object, *js_bigint(vm, end_ns)));
  381. // 12. Let endDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(relativeTo.[[TimeZone]], endInstant, relativeTo.[[Calendar]]).
  382. auto* end_date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, &relative_to.time_zone(), *end_instant, relative_to.calendar()));
  383. // 13. 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").
  384. 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));
  385. // 14. Let days be dateDifference.[[Days]].
  386. auto days = date_difference.days;
  387. // 15. Let intermediateNs be ℝ(? AddZonedDateTime(ℤ(startNs), relativeTo.[[TimeZone]], relativeTo.[[Calendar]], 0, 0, 0, days, 0, 0, 0, 0, 0, 0)).
  388. 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();
  389. // 16. If sign is 1, then
  390. if (sign == 1) {
  391. // a. Repeat, while days > 0 and intermediateNs > endNs,
  392. while (days > 0 && intermediate_ns > end_ns) {
  393. // i. Set days to days − 1.
  394. days--;
  395. // ii. Set intermediateNs to ℝ(? AddZonedDateTime(ℤ(startNs), relativeTo.[[TimeZone]], relativeTo.[[Calendar]], 0, 0, 0, days, 0, 0, 0, 0, 0, 0)).
  396. 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();
  397. }
  398. }
  399. // 17. Set nanoseconds to endNs − intermediateNs.
  400. nanoseconds = end_ns.minus(intermediate_ns);
  401. // 18. Let done be false.
  402. // 19. Repeat, while done is false,
  403. while (true) {
  404. // a. Let oneDayFartherNs be ℝ(? AddZonedDateTime(ℤ(intermediateNs), relativeTo.[[TimeZone]], relativeTo.[[Calendar]], 0, 0, 0, sign, 0, 0, 0, 0, 0, 0)).
  405. 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();
  406. // b. Set dayLengthNs to oneDayFartherNs − intermediateNs.
  407. day_length_ns = one_day_farther_ns.minus(intermediate_ns);
  408. // c. If (nanoseconds − dayLengthNs) × sign ≥ 0, then
  409. if (nanoseconds.minus(day_length_ns).multiplied_by(Crypto::SignedBigInteger { (i32)sign }) >= "0"_sbigint) {
  410. // i. Set nanoseconds to nanoseconds − dayLengthNs.
  411. nanoseconds = nanoseconds.minus(day_length_ns);
  412. // ii. Set intermediateNs to oneDayFartherNs.
  413. intermediate_ns = move(one_day_farther_ns);
  414. // iii. Set days to days + sign.
  415. days += sign;
  416. }
  417. // d. Else,
  418. else {
  419. // i. Set done to true.
  420. break;
  421. }
  422. }
  423. // 20. Return the Record { [[Days]]: days, [[Nanoseconds]]: nanoseconds, [[DayLength]]: abs(dayLengthNs) }.
  424. return NanosecondsToDaysResult { .days = days, .nanoseconds = move(nanoseconds), .day_length = fabs(day_length_ns.to_double()) };
  425. }
  426. }