DateTimeFormatConstructor.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /*
  2. * Copyright (c) 2021-2024, Tim Flynn <trflynn89@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/AbstractOperations.h>
  7. #include <LibJS/Runtime/Array.h>
  8. #include <LibJS/Runtime/Date.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. #include <LibJS/Runtime/Intl/AbstractOperations.h>
  11. #include <LibJS/Runtime/Intl/DateTimeFormat.h>
  12. #include <LibJS/Runtime/Intl/DateTimeFormatConstructor.h>
  13. #include <LibJS/Runtime/Temporal/ISO8601.h>
  14. #include <LibUnicode/DateTimeFormat.h>
  15. #include <LibUnicode/Locale.h>
  16. namespace JS::Intl {
  17. GC_DEFINE_ALLOCATOR(DateTimeFormatConstructor);
  18. // 11.1 The Intl.DateTimeFormat Constructor, https://tc39.es/ecma402/#sec-intl-datetimeformat-constructor
  19. DateTimeFormatConstructor::DateTimeFormatConstructor(Realm& realm)
  20. : NativeFunction(realm.vm().names.DateTimeFormat.as_string(), realm.intrinsics().function_prototype())
  21. {
  22. }
  23. void DateTimeFormatConstructor::initialize(Realm& realm)
  24. {
  25. Base::initialize(realm);
  26. auto& vm = this->vm();
  27. // 11.2.1 Intl.DateTimeFormat.prototype, https://tc39.es/ecma402/#sec-intl.datetimeformat.prototype
  28. define_direct_property(vm.names.prototype, realm.intrinsics().intl_date_time_format_prototype(), 0);
  29. u8 attr = Attribute::Writable | Attribute::Configurable;
  30. define_native_function(realm, vm.names.supportedLocalesOf, supported_locales_of, 1, attr);
  31. define_direct_property(vm.names.length, Value(0), Attribute::Configurable);
  32. }
  33. // 11.1.1 Intl.DateTimeFormat ( [ locales [ , options ] ] ), https://tc39.es/ecma402/#sec-intl.datetimeformat
  34. ThrowCompletionOr<Value> DateTimeFormatConstructor::call()
  35. {
  36. // 1. If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget.
  37. return TRY(construct(*this));
  38. }
  39. // 11.1.1 Intl.DateTimeFormat ( [ locales [ , options ] ] ), https://tc39.es/ecma402/#sec-intl.datetimeformat
  40. ThrowCompletionOr<GC::Ref<Object>> DateTimeFormatConstructor::construct(FunctionObject& new_target)
  41. {
  42. auto& vm = this->vm();
  43. auto locales = vm.argument(0);
  44. auto options = vm.argument(1);
  45. // 2. Let dateTimeFormat be ? CreateDateTimeFormat(newTarget, locales, options, ANY, DATE).
  46. auto date_time_format = TRY(create_date_time_format(vm, new_target, locales, options, OptionRequired::Any, OptionDefaults::Date));
  47. // 3. If the implementation supports the normative optional constructor mode of 4.3 Note 1, then
  48. // a. Let this be the this value.
  49. // b. Return ? ChainDateTimeFormat(dateTimeFormat, NewTarget, this).
  50. // 4. Return dateTimeFormat.
  51. return date_time_format;
  52. }
  53. // 11.2.2 Intl.DateTimeFormat.supportedLocalesOf ( locales [ , options ] ), https://tc39.es/ecma402/#sec-intl.datetimeformat.supportedlocalesof
  54. JS_DEFINE_NATIVE_FUNCTION(DateTimeFormatConstructor::supported_locales_of)
  55. {
  56. auto locales = vm.argument(0);
  57. auto options = vm.argument(1);
  58. // 1. Let availableLocales be %DateTimeFormat%.[[AvailableLocales]].
  59. // 2. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  60. auto requested_locales = TRY(canonicalize_locale_list(vm, locales));
  61. // 3. Return ? FilterLocales(availableLocales, requestedLocales, options).
  62. return TRY(filter_locales(vm, requested_locales, options));
  63. }
  64. // 11.1.2 CreateDateTimeFormat ( newTarget, locales, options, required, defaults ), https://tc39.es/ecma402/#sec-createdatetimeformat
  65. // 15.7.1 CreateDateTimeFormat ( newTarget, locales, options, required, defaults [ , toLocaleStringTimeZone ] ), https://tc39.es/proposal-temporal/#sec-createdatetimeformat
  66. ThrowCompletionOr<GC::Ref<DateTimeFormat>> create_date_time_format(VM& vm, FunctionObject& new_target, Value locales_value, Value options_value, OptionRequired required, OptionDefaults defaults, Optional<String> const& to_locale_string_time_zone)
  67. {
  68. // 1. Let dateTimeFormat be ? OrdinaryCreateFromConstructor(newTarget, "%Intl.DateTimeFormat.prototype%", « [[InitializedDateTimeFormat]], [[Locale]], [[Calendar]], [[NumberingSystem]], [[TimeZone]], [[HourCycle]], [[DateStyle]], [[TimeStyle]], [[DateTimeFormat]], [[BoundFormat]] »).
  69. auto date_time_format = TRY(ordinary_create_from_constructor<DateTimeFormat>(vm, new_target, &Intrinsics::intl_date_time_format_prototype));
  70. // 2. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  71. auto requested_locales = TRY(canonicalize_locale_list(vm, locales_value));
  72. // 3. Set options to ? CoerceOptionsToObject(options).
  73. auto* options = TRY(coerce_options_to_object(vm, options_value));
  74. // 4. Let opt be a new Record.
  75. LocaleOptions opt {};
  76. // 5. Let matcher be ? GetOption(options, "localeMatcher", string, « "lookup", "best fit" », "best fit").
  77. auto matcher = TRY(get_option(vm, *options, vm.names.localeMatcher, OptionType::String, AK::Array { "lookup"sv, "best fit"sv }, "best fit"sv));
  78. // 6. Set opt.[[localeMatcher]] to matcher.
  79. opt.locale_matcher = matcher;
  80. // 7. Let calendar be ? GetOption(options, "calendar", string, empty, undefined).
  81. auto calendar = TRY(get_option(vm, *options, vm.names.calendar, OptionType::String, {}, Empty {}));
  82. // 8. If calendar is not undefined, then
  83. if (!calendar.is_undefined()) {
  84. // a. If calendar cannot be matched by the type Unicode locale nonterminal, throw a RangeError exception.
  85. if (!Unicode::is_type_identifier(calendar.as_string().utf8_string_view()))
  86. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, calendar, "calendar"sv);
  87. }
  88. // 9. Set opt.[[ca]] to calendar.
  89. opt.ca = locale_key_from_value(calendar);
  90. // 10. Let numberingSystem be ? GetOption(options, "numberingSystem", string, empty, undefined).
  91. auto numbering_system = TRY(get_option(vm, *options, vm.names.numberingSystem, OptionType::String, {}, Empty {}));
  92. // 11. If numberingSystem is not undefined, then
  93. if (!numbering_system.is_undefined()) {
  94. // a. If numberingSystem cannot be matched by the type Unicode locale nonterminal, throw a RangeError exception.
  95. if (!Unicode::is_type_identifier(numbering_system.as_string().utf8_string_view()))
  96. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, numbering_system, "numberingSystem"sv);
  97. }
  98. // 12. Set opt.[[nu]] to numberingSystem.
  99. opt.nu = locale_key_from_value(numbering_system);
  100. // 13. Let hour12 be ? GetOption(options, "hour12", boolean, empty, undefined).
  101. auto hour12 = TRY(get_option(vm, *options, vm.names.hour12, OptionType::Boolean, {}, Empty {}));
  102. // 14. Let hourCycle be ? GetOption(options, "hourCycle", string, « "h11", "h12", "h23", "h24" », undefined).
  103. auto hour_cycle = TRY(get_option(vm, *options, vm.names.hourCycle, OptionType::String, AK::Array { "h11"sv, "h12"sv, "h23"sv, "h24"sv }, Empty {}));
  104. // 15. If hour12 is not undefined, then
  105. if (!hour12.is_undefined()) {
  106. // a. Set hourCycle to null.
  107. hour_cycle = js_null();
  108. }
  109. // 16. Set opt.[[hc]] to hourCycle.
  110. opt.hc = locale_key_from_value(hour_cycle);
  111. // 17. Let r be ResolveLocale(%Intl.DateTimeFormat%.[[AvailableLocales]], requestedLocales, opt, %Intl.DateTimeFormat%.[[RelevantExtensionKeys]], %Intl.DateTimeFormat%.[[LocaleData]]).
  112. auto result = resolve_locale(requested_locales, opt, DateTimeFormat::relevant_extension_keys());
  113. // 18. Set dateTimeFormat.[[Locale]] to r.[[Locale]].
  114. date_time_format->set_locale(move(result.locale));
  115. // 19. Let resolvedCalendar be r.[[ca]].
  116. // 20. Set dateTimeFormat.[[Calendar]] to resolvedCalendar.
  117. if (auto* resolved_calendar = result.ca.get_pointer<String>())
  118. date_time_format->set_calendar(move(*resolved_calendar));
  119. // 21. Set dateTimeFormat.[[NumberingSystem]] to r.[[nu]].
  120. if (auto* resolved_numbering_system = result.nu.get_pointer<String>())
  121. date_time_format->set_numbering_system(move(*resolved_numbering_system));
  122. // 22. Let resolvedLocaleData be r.[[LocaleData]].
  123. Optional<Unicode::HourCycle> hour_cycle_value;
  124. Optional<bool> hour12_value;
  125. // 23. If hour12 is true, then
  126. // a. Let hc be resolvedLocaleData.[[hourCycle12]].
  127. // 24. Else if hour12 is false, then
  128. // a. Let hc be resolvedLocaleData.[[hourCycle24]].
  129. if (hour12.is_boolean()) {
  130. // NOTE: We let LibUnicode figure out the appropriate hour cycle.
  131. hour12_value = hour12.as_bool();
  132. }
  133. // 25. Else,
  134. else {
  135. // a. Assert: hour12 is undefined.
  136. VERIFY(hour12.is_undefined());
  137. // b. Let hc be r.[[hc]].
  138. if (auto* resolved_hour_cycle = result.hc.get_pointer<String>())
  139. hour_cycle_value = Unicode::hour_cycle_from_string(*resolved_hour_cycle);
  140. // c. If hc is null, set hc to resolvedLocaleData.[[hourCycle]].
  141. if (!hour_cycle_value.has_value())
  142. hour_cycle_value = Unicode::default_hour_cycle(date_time_format->locale());
  143. }
  144. // 26. Set dateTimeFormat.[[HourCycle]] to hc.
  145. // NOTE: The [[HourCycle]] is stored and accessed from [[DateTimeFormat]].
  146. // 27. Let timeZone be ? Get(options, "timeZone").
  147. auto time_zone_value = TRY(options->get(vm.names.timeZone));
  148. String time_zone;
  149. // 28. If timeZone is undefined, then
  150. if (time_zone_value.is_undefined()) {
  151. // a. If toLocaleStringTimeZone is present, then
  152. if (to_locale_string_time_zone.has_value()) {
  153. // i. Set timeZone to toLocaleStringTimeZone.
  154. time_zone = *to_locale_string_time_zone;
  155. }
  156. // b. Else,
  157. else {
  158. // i. Set timeZone to SystemTimeZoneIdentifier().
  159. time_zone = system_time_zone_identifier();
  160. }
  161. }
  162. // 29. Else,
  163. else {
  164. // a. If toLocaleStringTimeZone is present, throw a TypeError exception.
  165. if (to_locale_string_time_zone.has_value())
  166. return vm.throw_completion<TypeError>(ErrorType::IntlInvalidDateTimeFormatOption, vm.names.timeZone, "a toLocaleString time zone"sv);
  167. // b. Set timeZone to ? ToString(timeZone).
  168. time_zone = TRY(time_zone_value.to_string(vm));
  169. }
  170. // 30. If IsTimeZoneOffsetString(timeZone) is true, then
  171. bool is_time_zone_offset_string = JS::is_offset_time_zone_identifier(time_zone);
  172. if (is_time_zone_offset_string) {
  173. // a. Let parseResult be ParseText(StringToCodePoints(timeZone), UTCOffset[~SubMinutePrecision]).
  174. auto parse_result = Temporal::parse_utc_offset(time_zone, Temporal::SubMinutePrecision::No);
  175. // b. Assert: parseResult is a Parse Node.
  176. VERIFY(parse_result.has_value());
  177. // c. Let offsetNanoseconds be ? ParseDateTimeUTCOffset(timeZone).
  178. auto offset_nanoseconds = TRY(parse_date_time_utc_offset(vm, time_zone));
  179. // d. Let offsetMinutes be offsetNanoseconds / (6 × 10**10).
  180. auto offset_minutes = offset_nanoseconds / 60'000'000'000;
  181. // e. Assert: offsetMinutes is an integer.
  182. VERIFY(trunc(offset_minutes) == offset_minutes);
  183. // f. Set timeZone to FormatOffsetTimeZoneIdentifier(offsetMinutes).
  184. time_zone = format_offset_time_zone_identifier(offset_minutes);
  185. }
  186. // 31. Else,
  187. else {
  188. // a. Let timeZoneIdentifierRecord be GetAvailableNamedTimeZoneIdentifier(timeZone).
  189. auto time_zone_identifier_record = get_available_named_time_zone_identifier(time_zone);
  190. // b. If timeZoneIdentifierRecord is EMPTY, throw a RangeError exception.
  191. if (!time_zone_identifier_record.has_value())
  192. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, time_zone, vm.names.timeZone);
  193. // c. Set timeZone to timeZoneIdentifierRecord.[[PrimaryIdentifier]].
  194. time_zone = time_zone_identifier_record->primary_identifier;
  195. }
  196. // 32. Set dateTimeFormat.[[TimeZone]] to timeZone.
  197. date_time_format->set_time_zone(time_zone);
  198. // NOTE: ICU requires time zone offset strings to be of the form "GMT+00:00"
  199. if (is_time_zone_offset_string)
  200. time_zone = MUST(String::formatted("GMT{}", time_zone));
  201. // AD-HOC: We must store the massaged time zone for creating ICU formatters for Temporal objects.
  202. date_time_format->set_temporal_time_zone(time_zone);
  203. // 33. Let formatOptions be a new Record.
  204. Unicode::CalendarPattern format_options {};
  205. // 34. Set formatOptions.[[hourCycle]] to hc.
  206. format_options.hour_cycle = hour_cycle_value;
  207. format_options.hour12 = hour12_value;
  208. // 35. Let hasExplicitFormatComponents be false.
  209. // NOTE: Instead of using a boolean, we track any explicitly provided component name for nicer exception messages.
  210. PropertyKey const* explicit_format_component = nullptr;
  211. // 36. For each row of Table 16, except the header row, in table order, do
  212. TRY(for_each_calendar_field(vm, format_options, [&](auto& option, PropertyKey const& property, auto const& values) -> ThrowCompletionOr<void> {
  213. using ValueType = typename RemoveReference<decltype(option)>::ValueType;
  214. // a. Let prop be the name given in the Property column of the current row.
  215. // b. If prop is "fractionalSecondDigits", then
  216. if constexpr (IsIntegral<ValueType>) {
  217. // i. Let value be ? GetNumberOption(options, "fractionalSecondDigits", 1, 3, undefined).
  218. auto value = TRY(get_number_option(vm, *options, property, 1, 3, {}));
  219. // d. Set formatOptions.[[<prop>]] to value.
  220. if (value.has_value()) {
  221. option = static_cast<ValueType>(value.value());
  222. // e. If value is not undefined, then
  223. // i. Set hasExplicitFormatComponents to true.
  224. explicit_format_component = &property;
  225. }
  226. }
  227. // c. Else,
  228. else {
  229. // i. Let values be a List whose elements are the strings given in the Values column of the current row.
  230. // ii. Let value be ? GetOption(options, prop, string, values, undefined).
  231. auto value = TRY(get_option(vm, *options, property, OptionType::String, values, Empty {}));
  232. // d. Set formatOptions.[[<prop>]] to value.
  233. if (!value.is_undefined()) {
  234. option = Unicode::calendar_pattern_style_from_string(value.as_string().utf8_string_view());
  235. // e. If value is not undefined, then
  236. // i. Set hasExplicitFormatComponents to true.
  237. explicit_format_component = &property;
  238. }
  239. }
  240. return {};
  241. }));
  242. // 37. Let formatMatcher be ? GetOption(options, "formatMatcher", string, « "basic", "best fit" », "best fit").
  243. [[maybe_unused]] auto format_matcher = TRY(get_option(vm, *options, vm.names.formatMatcher, OptionType::String, AK::Array { "basic"sv, "best fit"sv }, "best fit"sv));
  244. // 38. Let dateStyle be ? GetOption(options, "dateStyle", string, « "full", "long", "medium", "short" », undefined).
  245. auto date_style = TRY(get_option(vm, *options, vm.names.dateStyle, OptionType::String, AK::Array { "full"sv, "long"sv, "medium"sv, "short"sv }, Empty {}));
  246. // 39. Set dateTimeFormat.[[DateStyle]] to dateStyle.
  247. if (!date_style.is_undefined())
  248. date_time_format->set_date_style(date_style.as_string().utf8_string_view());
  249. // 40. Let timeStyle be ? GetOption(options, "timeStyle", string, « "full", "long", "medium", "short" », undefined).
  250. auto time_style = TRY(get_option(vm, *options, vm.names.timeStyle, OptionType::String, AK::Array { "full"sv, "long"sv, "medium"sv, "short"sv }, Empty {}));
  251. // 41. Set dateTimeFormat.[[TimeStyle]] to timeStyle.
  252. if (!time_style.is_undefined())
  253. date_time_format->set_time_style(time_style.as_string().utf8_string_view());
  254. // 42. Let formats be resolvedLocaleData.[[formats]].[[<resolvedCalendar>]].
  255. OwnPtr<Unicode::DateTimeFormat> formatter;
  256. // 43. If dateStyle is not undefined or timeStyle is not undefined, then
  257. if (date_time_format->has_date_style() || date_time_format->has_time_style()) {
  258. // a. If hasExplicitFormatComponents is true, then
  259. if (explicit_format_component != nullptr) {
  260. // i. Throw a TypeError exception.
  261. return vm.throw_completion<TypeError>(ErrorType::IntlInvalidDateTimeFormatOption, *explicit_format_component, "dateStyle or timeStyle"sv);
  262. }
  263. // b. If required is date and timeStyle is not undefined, then
  264. if (required == OptionRequired::Date && !time_style.is_undefined()) {
  265. // i. Throw a TypeError exception.
  266. return vm.throw_completion<TypeError>(ErrorType::IntlInvalidDateTimeFormatOption, "timeStyle"sv, "date"sv);
  267. }
  268. // c. If required is time and dateStyle is not undefined, then
  269. if (required == OptionRequired::Time && !date_style.is_undefined()) {
  270. // i. Throw a TypeError exception.
  271. return vm.throw_completion<TypeError>(ErrorType::IntlInvalidDateTimeFormatOption, "dateStyle"sv, "time"sv);
  272. }
  273. // d. Let styles be resolvedLocaleData.[[styles]].[[<resolvedCalendar>]].
  274. // e. Let bestFormat be DateTimeStyleFormat(dateStyle, timeStyle, styles).
  275. formatter = Unicode::DateTimeFormat::create_for_date_and_time_style(
  276. date_time_format->locale(),
  277. time_zone,
  278. format_options.hour_cycle,
  279. format_options.hour12,
  280. date_time_format->date_style(),
  281. date_time_format->time_style());
  282. auto best_format = formatter->chosen_pattern();
  283. using enum Unicode::CalendarPattern::Field;
  284. // f. If dateStyle is not undefined, then
  285. if (!date_style.is_undefined()) {
  286. // i. Set dateTimeFormat.[[TemporalPlainDateFormat]] to AdjustDateTimeStyleFormat(formats, bestFormat, formatMatcher, « [[weekday]], [[era]], [[year]], [[month]], [[day]] »).
  287. auto temporal_plain_date_format = adjust_date_time_style_format(best_format, { { Weekday, Era, Year, Month, Day } });
  288. date_time_format->set_temporal_plain_date_format(move(temporal_plain_date_format));
  289. // ii. Set dateTimeFormat.[[TemporalPlainYearMonthFormat]] to AdjustDateTimeStyleFormat(formats, bestFormat, formatMatcher, « [[era]], [[year]], [[month]] »).
  290. auto temporal_plain_year_month_format = adjust_date_time_style_format(best_format, { { Era, Year, Month } });
  291. date_time_format->set_temporal_plain_year_month_format(move(temporal_plain_year_month_format));
  292. // iii. Set dateTimeFormat.[[TemporalPlainMonthDayFormat]] to AdjustDateTimeStyleFormat(formats, bestFormat, formatMatcher, « [[month]], [[day]] »).
  293. auto temporal_plain_month_day_format = adjust_date_time_style_format(best_format, { { Month, Day } });
  294. date_time_format->set_temporal_plain_month_day_format(move(temporal_plain_month_day_format));
  295. }
  296. // g. Else,
  297. else {
  298. // i. Set dateTimeFormat.[[TemporalPlainDateFormat]] to null.
  299. // ii. Set dateTimeFormat.[[TemporalPlainYearMonthFormat]] to null.
  300. // iii. Set dateTimeFormat.[[TemporalPlainMonthDayFormat]] to null.
  301. }
  302. // h. If timeStyle is not undefined, then
  303. if (!time_style.is_undefined()) {
  304. // i. Set dateTimeFormat.[[TemporalPlainTimeFormat]] to AdjustDateTimeStyleFormat(formats, bestFormat, formatMatcher, « [[dayPeriod]], [[hour]], [[minute]], [[second]], [[fractionalSecondDigits]] »).
  305. auto temporal_plain_time_format = adjust_date_time_style_format(best_format, { { DayPeriod, Hour, Minute, Second, FractionalSecondDigits } });
  306. date_time_format->set_temporal_plain_time_format(move(temporal_plain_time_format));
  307. }
  308. // i. Else,
  309. else {
  310. // i. Set dateTimeFormat.[[TemporalPlainTimeFormat]] to null.
  311. }
  312. // j. Set dateTimeFormat.[[TemporalPlainDateTimeFormat]] to AdjustDateTimeStyleFormat(formats, bestFormat, formatMatcher, « [[weekday]], [[era]], [[year]], [[month]], [[day]], [[dayPeriod]], [[hour]], [[minute]], [[second]], [[fractionalSecondDigits]] »).
  313. auto temporal_plain_date_time_format = adjust_date_time_style_format(best_format, { { Weekday, Era, Year, Month, Day, DayPeriod, Hour, Minute, Second, FractionalSecondDigits } });
  314. date_time_format->set_temporal_plain_date_time_format(move(temporal_plain_date_time_format));
  315. // k. Set dateTimeFormat.[[TemporalInstantFormat]] to bestFormat.
  316. date_time_format->set_temporal_instant_format(move(best_format));
  317. }
  318. // 44. Else,
  319. else {
  320. // a. Let bestFormat be GetDateTimeFormat(formats, formatMatcher, formatOptions, required, defaults, ALL).
  321. auto best_format = get_date_time_format(format_options, required, defaults, OptionInherit::All).release_value();
  322. // b. Set dateTimeFormat.[[TemporalPlainDateFormat]] to GetDateTimeFormat(formats, formatMatcher, formatOptions, DATE, DATE, RELEVANT).
  323. auto temporal_plain_date_format = get_date_time_format(format_options, OptionRequired::Date, OptionDefaults::Date, OptionInherit::Relevant);
  324. date_time_format->set_temporal_plain_date_format(move(temporal_plain_date_format));
  325. // c. Set dateTimeFormat.[[TemporalPlainYearMonthFormat]] to GetDateTimeFormat(formats, formatMatcher, formatOptions, YEAR-MONTH, YEAR-MONTH, RELEVANT).
  326. auto temporal_plain_year_month_format = get_date_time_format(format_options, OptionRequired::YearMonth, OptionDefaults::YearMonth, OptionInherit::Relevant);
  327. date_time_format->set_temporal_plain_year_month_format(move(temporal_plain_year_month_format));
  328. // d. Set dateTimeFormat.[[TemporalPlainMonthDayFormat]] to GetDateTimeFormat(formats, formatMatcher, formatOptions, MONTH-DAY, MONTH-DAY, RELEVANT).
  329. auto temporal_plain_month_day_format = get_date_time_format(format_options, OptionRequired::MonthDay, OptionDefaults::MonthDay, OptionInherit::Relevant);
  330. date_time_format->set_temporal_plain_month_day_format(move(temporal_plain_month_day_format));
  331. // e. Set dateTimeFormat.[[TemporalPlainTimeFormat]] to GetDateTimeFormat(formats, formatMatcher, formatOptions, TIME, TIME, RELEVANT).
  332. auto temporal_plain_time_format = get_date_time_format(format_options, OptionRequired::Time, OptionDefaults::Time, OptionInherit::Relevant);
  333. date_time_format->set_temporal_plain_time_format(move(temporal_plain_time_format));
  334. // f. Set dateTimeFormat.[[TemporalPlainDateTimeFormat]] to GetDateTimeFormat(formats, formatMatcher, formatOptions, ANY, ALL, RELEVANT).
  335. auto temporal_plain_date_time_format = get_date_time_format(format_options, OptionRequired::Any, OptionDefaults::All, OptionInherit::Relevant);
  336. date_time_format->set_temporal_plain_date_time_format(move(temporal_plain_date_time_format));
  337. // g. If toLocaleStringTimeZone is present, then
  338. if (to_locale_string_time_zone.has_value()) {
  339. // i. Set dateTimeFormat.[[TemporalInstantFormat]] to GetDateTimeFormat(formats, formatMatcher, formatOptions, ANY, ZONED-DATE-TIME, ALL).
  340. auto temporal_instant_format = get_date_time_format(format_options, OptionRequired::Any, OptionDefaults::ZonedDateTime, OptionInherit::All);
  341. date_time_format->set_temporal_instant_format(move(temporal_instant_format));
  342. }
  343. // h. Else,
  344. else {
  345. // i. Set dateTimeFormat.[[TemporalInstantFormat]] to GetDateTimeFormat(formats, formatMatcher, formatOptions, ANY, ALL, ALL).
  346. auto temporal_instant_format = get_date_time_format(format_options, OptionRequired::Any, OptionDefaults::All, OptionInherit::All);
  347. date_time_format->set_temporal_instant_format(move(temporal_instant_format));
  348. }
  349. formatter = Unicode::DateTimeFormat::create_for_pattern_options(
  350. date_time_format->locale(),
  351. time_zone,
  352. best_format);
  353. }
  354. // 45. Set dateTimeFormat.[[DateTimeFormat]] to bestFormat.
  355. date_time_format->set_date_time_format(formatter->chosen_pattern());
  356. // Non-standard, create an ICU number formatter for this Intl object.
  357. date_time_format->set_formatter(formatter.release_nonnull());
  358. // 46. Return dateTimeFormat.
  359. return date_time_format;
  360. }
  361. // 11.1.3 FormatOffsetTimeZoneIdentifier ( offsetMinutes ), https://tc39.es/ecma402/#sec-formatoffsettimezoneidentifier
  362. String format_offset_time_zone_identifier(double offset_minutes)
  363. {
  364. // 1. If offsetMinutes ≥ 0, let sign be the code unit 0x002B (PLUS SIGN); otherwise, let sign be the code unit 0x002D (HYPHEN-MINUS).
  365. auto sign = offset_minutes >= 0.0 ? '+' : '-';
  366. // 2. Let absoluteMinutes be abs(offsetMinutes).
  367. auto absolute_minutes = fabs(offset_minutes);
  368. // 3. Let hours be floor(absoluteMinutes / 60).
  369. auto hours = static_cast<i64>(floor(absolute_minutes / 60.0));
  370. // 4. Let minutes be absoluteMinutes modulo 60.
  371. auto minutes = static_cast<i64>(modulo(absolute_minutes, 60.0));
  372. // 5. Return the string-concatenation of sign, ToZeroPaddedDecimalString(hours, 2), the code unit 0x003A (COLON), and ToZeroPaddedDecimalString(minutes, 2).
  373. return MUST(String::formatted("{}{:02}:{:02}", sign, hours, minutes));
  374. }
  375. }