DateTimeFormatConstructor.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. /*
  2. * Copyright (c) 2021-2023, Tim Flynn <trflynn89@serenityos.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/TimeZone.h>
  14. #include <LibLocale/DateTimeFormat.h>
  15. #include <LibLocale/Locale.h>
  16. namespace JS::Intl {
  17. JS_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<NonnullGCPtr<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 ? SupportedLocales(availableLocales, requestedLocales, options).
  62. return TRY(supported_locales(vm, requested_locales, options));
  63. }
  64. // 11.1.2 CreateDateTimeFormat ( newTarget, locales, options, required, defaults ), https://tc39.es/ecma402/#sec-createdatetimeformat
  65. ThrowCompletionOr<NonnullGCPtr<DateTimeFormat>> create_date_time_format(VM& vm, FunctionObject& new_target, Value locales_value, Value options_value, OptionRequired required, OptionDefaults defaults)
  66. {
  67. // 1. Let dateTimeFormat be ? OrdinaryCreateFromConstructor(newTarget, "%DateTimeFormat.prototype%", « [[InitializedDateTimeFormat]], [[Locale]], [[Calendar]], [[NumberingSystem]], [[TimeZone]], [[Weekday]], [[Era]], [[Year]], [[Month]], [[Day]], [[DayPeriod]], [[Hour]], [[Minute]], [[Second]], [[FractionalSecondDigits]], [[TimeZoneName]], [[HourCycle]], [[DateStyle]], [[TimeStyle]], [[Pattern]], [[RangePatterns]], [[BoundFormat]] »).
  68. auto date_time_format = TRY(ordinary_create_from_constructor<DateTimeFormat>(vm, new_target, &Intrinsics::intl_date_time_format_prototype));
  69. // 2. Let requestedLocales be ? CanonicalizeLocaleList(locales).
  70. auto requested_locales = TRY(canonicalize_locale_list(vm, locales_value));
  71. // 3. Set options to ? CoerceOptionsToObject(options).
  72. auto* options = TRY(coerce_options_to_object(vm, options_value));
  73. // 4. Let opt be a new Record.
  74. LocaleOptions opt {};
  75. // 5. Let matcher be ? GetOption(options, "localeMatcher", string, « "lookup", "best fit" », "best fit").
  76. auto matcher = TRY(get_option(vm, *options, vm.names.localeMatcher, OptionType::String, AK::Array { "lookup"sv, "best fit"sv }, "best fit"sv));
  77. // 6. Set opt.[[localeMatcher]] to matcher.
  78. opt.locale_matcher = matcher;
  79. // 7. Let calendar be ? GetOption(options, "calendar", string, empty, undefined).
  80. auto calendar = TRY(get_option(vm, *options, vm.names.calendar, OptionType::String, {}, Empty {}));
  81. // 8. If calendar is not undefined, then
  82. if (!calendar.is_undefined()) {
  83. // a. If calendar cannot be matched by the type Unicode locale nonterminal, throw a RangeError exception.
  84. if (!::Locale::is_type_identifier(calendar.as_string().utf8_string_view()))
  85. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, calendar, "calendar"sv);
  86. // 9. Set opt.[[ca]] to calendar.
  87. opt.ca = calendar.as_string().utf8_string();
  88. }
  89. // 10. Let numberingSystem be ? GetOption(options, "numberingSystem", string, empty, undefined).
  90. auto numbering_system = TRY(get_option(vm, *options, vm.names.numberingSystem, OptionType::String, {}, Empty {}));
  91. // 11. If numberingSystem is not undefined, then
  92. if (!numbering_system.is_undefined()) {
  93. // a. If numberingSystem cannot be matched by the type Unicode locale nonterminal, throw a RangeError exception.
  94. if (!::Locale::is_type_identifier(numbering_system.as_string().utf8_string_view()))
  95. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, numbering_system, "numberingSystem"sv);
  96. // 12. Set opt.[[nu]] to numberingSystem.
  97. opt.nu = numbering_system.as_string().utf8_string();
  98. }
  99. // 13. Let hour12 be ? GetOption(options, "hour12", boolean, empty, undefined).
  100. auto hour12 = TRY(get_option(vm, *options, vm.names.hour12, OptionType::Boolean, {}, Empty {}));
  101. // 14. Let hourCycle be ? GetOption(options, "hourCycle", string, « "h11", "h12", "h23", "h24" », undefined).
  102. auto hour_cycle = TRY(get_option(vm, *options, vm.names.hourCycle, OptionType::String, AK::Array { "h11"sv, "h12"sv, "h23"sv, "h24"sv }, Empty {}));
  103. // 15. If hour12 is not undefined, then
  104. if (!hour12.is_undefined()) {
  105. // a. Set hourCycle to null.
  106. hour_cycle = js_null();
  107. }
  108. // 16. Set opt.[[hc]] to hourCycle.
  109. if (!hour_cycle.is_nullish())
  110. opt.hc = hour_cycle.as_string().utf8_string();
  111. // 17. Let localeData be %DateTimeFormat%.[[LocaleData]].
  112. // 18. Let r be ResolveLocale(%DateTimeFormat%.[[AvailableLocales]], requestedLocales, opt, %DateTimeFormat%.[[RelevantExtensionKeys]], localeData).
  113. auto result = resolve_locale(requested_locales, opt, DateTimeFormat::relevant_extension_keys());
  114. // 19. Set dateTimeFormat.[[Locale]] to r.[[locale]].
  115. date_time_format->set_locale(move(result.locale));
  116. // 20. Let resolvedCalendar be r.[[ca]].
  117. // 21. Set dateTimeFormat.[[Calendar]] to resolvedCalendar.
  118. if (result.ca.has_value())
  119. date_time_format->set_calendar(result.ca.release_value());
  120. // 22. Set dateTimeFormat.[[NumberingSystem]] to r.[[nu]].
  121. if (result.nu.has_value())
  122. date_time_format->set_numbering_system(result.nu.release_value());
  123. // 23. Let dataLocale be r.[[dataLocale]].
  124. auto data_locale = move(result.data_locale);
  125. // Non-standard, the data locale is needed for LibUnicode lookups while formatting.
  126. date_time_format->set_data_locale(data_locale);
  127. // 24. Let dataLocaleData be localeData.[[<dataLocale>]].
  128. Optional<::Locale::HourCycle> hour_cycle_value;
  129. auto set_locale_hour_cycle = [&](auto... candidate_hour_cycles) {
  130. // Locale hour cycles (parsed from timeData.json) are stored in preference order. Use the
  131. // first hour cycle that matches any of the provided candidates. There may be no matches if
  132. // e.g. Unicode data generation is disabled.
  133. auto locale_hour_cycles = ::Locale::get_locale_hour_cycles(data_locale);
  134. auto index = locale_hour_cycles.find_first_index_if([&](auto hour_cycle) {
  135. return ((hour_cycle == candidate_hour_cycles) || ...);
  136. });
  137. if (index.has_value())
  138. hour_cycle_value = locale_hour_cycles[*index];
  139. };
  140. // 25. If hour12 is true, then
  141. if (hour12.is_boolean() && hour12.as_bool()) {
  142. // a. Let hc be dataLocaleData.[[hourCycle12]].
  143. set_locale_hour_cycle(::Locale::HourCycle::H11, ::Locale::HourCycle::H12);
  144. }
  145. // 26. Else if hour12 is false, then
  146. else if (hour12.is_boolean() && !hour12.as_bool()) {
  147. // a. Let hc be dataLocaleData.[[hourCycle24]].
  148. set_locale_hour_cycle(::Locale::HourCycle::H23, ::Locale::HourCycle::H24);
  149. }
  150. // 27. Else,
  151. else {
  152. // a. Assert: hour12 is undefined.
  153. VERIFY(hour12.is_undefined());
  154. // b. Let hc be r.[[hc]].
  155. if (result.hc.has_value())
  156. hour_cycle_value = ::Locale::hour_cycle_from_string(*result.hc);
  157. // c. If hc is null, set hc to dataLocaleData.[[hourCycle]].
  158. if (!hour_cycle_value.has_value())
  159. hour_cycle_value = ::Locale::get_default_regional_hour_cycle(data_locale);
  160. }
  161. // 28. Set dateTimeFormat.[[HourCycle]] to hc.
  162. if (hour_cycle_value.has_value())
  163. date_time_format->set_hour_cycle(*hour_cycle_value);
  164. // 29. Let timeZone be ? Get(options, "timeZone").
  165. auto time_zone_value = TRY(options->get(vm.names.timeZone));
  166. String time_zone;
  167. // 30. If timeZone is undefined, then
  168. if (time_zone_value.is_undefined()) {
  169. // a. Set timeZone to DefaultTimeZone().
  170. time_zone = MUST(String::from_utf8(system_time_zone_identifier()));
  171. }
  172. // 31. Else,
  173. else {
  174. // a. Set timeZone to ? ToString(timeZone).
  175. time_zone = TRY(time_zone_value.to_string(vm));
  176. }
  177. // 32. If IsTimeZoneOffsetString(timeZone) is true, then
  178. if (is_time_zone_offset_string(time_zone)) {
  179. // a. Let parseResult be ParseText(StringToCodePoints(timeZone), UTCOffset).
  180. auto parse_result = Temporal::parse_iso8601(Temporal::Production::TimeZoneNumericUTCOffset, time_zone);
  181. // b. Assert: parseResult is a Parse Node.
  182. VERIFY(parse_result.has_value());
  183. // c. If parseResult contains more than one MinuteSecond Parse Node, throw a RangeError exception.
  184. if (parse_result->time_zone_utc_offset_second.has_value())
  185. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, time_zone, vm.names.timeZone);
  186. // d. Let offsetNanoseconds be ParseTimeZoneOffsetString(timeZone).
  187. auto offset_nanoseconds = parse_time_zone_offset_string(time_zone);
  188. // e. Let offsetMinutes be offsetNanoseconds / (6 × 10^10).
  189. auto offset_minutes = offset_nanoseconds / 60'000'000'000;
  190. // f. Assert: offsetMinutes is an integer.
  191. VERIFY(trunc(offset_minutes) == offset_minutes);
  192. // g. Set timeZone to FormatOffsetTimeZoneIdentifier(offsetMinutes).
  193. time_zone = format_offset_time_zone_identifier(offset_minutes);
  194. }
  195. // 33. Else if IsValidTimeZoneName(timeZone) is true, then
  196. else if (Temporal::is_available_time_zone_name(time_zone)) {
  197. // a. Set timeZone to CanonicalizeTimeZoneName(timeZone).
  198. time_zone = MUST(Temporal::canonicalize_time_zone_name(vm, time_zone));
  199. }
  200. // 34. Else,
  201. else {
  202. // a. Throw a RangeError exception.
  203. return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, time_zone, vm.names.timeZone);
  204. }
  205. // 35. Set dateTimeFormat.[[TimeZone]] to timeZone.
  206. date_time_format->set_time_zone(move(time_zone));
  207. // 36. Let formatOptions be a new Record.
  208. ::Locale::CalendarPattern format_options {};
  209. // 37. Set formatOptions.[[hourCycle]] to hc.
  210. format_options.hour_cycle = hour_cycle_value;
  211. // 38. Let hasExplicitFormatComponents be false.
  212. // NOTE: Instead of using a boolean, we track any explicitly provided component name for nicer exception messages.
  213. PropertyKey const* explicit_format_component = nullptr;
  214. // 39. For each row of Table 6, except the header row, in table order, do
  215. TRY(for_each_calendar_field(vm, format_options, [&](auto& option, PropertyKey const& property, auto const& values) -> ThrowCompletionOr<void> {
  216. using ValueType = typename RemoveReference<decltype(option)>::ValueType;
  217. // a. Let prop be the name given in the Property column of the row.
  218. // b. If prop is "fractionalSecondDigits", then
  219. if constexpr (IsIntegral<ValueType>) {
  220. // i. Let value be ? GetNumberOption(options, "fractionalSecondDigits", 1, 3, undefined).
  221. auto value = TRY(get_number_option(vm, *options, property, 1, 3, {}));
  222. // d. Set formatOptions.[[<prop>]] to value.
  223. if (value.has_value()) {
  224. option = static_cast<ValueType>(value.value());
  225. // e. If value is not undefined, then
  226. // i. Set hasExplicitFormatComponents to true.
  227. explicit_format_component = &property;
  228. }
  229. }
  230. // c. Else,
  231. else {
  232. // i. Let values be a List whose elements are the strings given in the Values column of the row.
  233. // ii. Let value be ? GetOption(options, prop, string, values, undefined).
  234. auto value = TRY(get_option(vm, *options, property, OptionType::String, values, Empty {}));
  235. // d. Set formatOptions.[[<prop>]] to value.
  236. if (!value.is_undefined()) {
  237. option = ::Locale::calendar_pattern_style_from_string(value.as_string().utf8_string_view());
  238. // e. If value is not undefined, then
  239. // i. Set hasExplicitFormatComponents to true.
  240. explicit_format_component = &property;
  241. }
  242. }
  243. return {};
  244. }));
  245. // 40. Let matcher be ? GetOption(options, "formatMatcher", string, « "basic", "best fit" », "best fit").
  246. matcher = TRY(get_option(vm, *options, vm.names.formatMatcher, OptionType::String, AK::Array { "basic"sv, "best fit"sv }, "best fit"sv));
  247. // 41. Let dateStyle be ? GetOption(options, "dateStyle", string, « "full", "long", "medium", "short" », undefined).
  248. auto date_style = TRY(get_option(vm, *options, vm.names.dateStyle, OptionType::String, AK::Array { "full"sv, "long"sv, "medium"sv, "short"sv }, Empty {}));
  249. // 42. Set dateTimeFormat.[[DateStyle]] to dateStyle.
  250. if (!date_style.is_undefined())
  251. date_time_format->set_date_style(date_style.as_string().utf8_string_view());
  252. // 43. Let timeStyle be ? GetOption(options, "timeStyle", string, « "full", "long", "medium", "short" », undefined).
  253. auto time_style = TRY(get_option(vm, *options, vm.names.timeStyle, OptionType::String, AK::Array { "full"sv, "long"sv, "medium"sv, "short"sv }, Empty {}));
  254. // 44. Set dateTimeFormat.[[TimeStyle]] to timeStyle.
  255. if (!time_style.is_undefined())
  256. date_time_format->set_time_style(time_style.as_string().utf8_string_view());
  257. Optional<::Locale::CalendarPattern> best_format {};
  258. // 45. If dateStyle is not undefined or timeStyle is not undefined, then
  259. if (date_time_format->has_date_style() || date_time_format->has_time_style()) {
  260. // a. If hasExplicitFormatComponents is true, then
  261. if (explicit_format_component != nullptr) {
  262. // i. Throw a TypeError exception.
  263. return vm.throw_completion<TypeError>(ErrorType::IntlInvalidDateTimeFormatOption, *explicit_format_component, "dateStyle or timeStyle"sv);
  264. }
  265. // b. If required is date and timeStyle is not undefined, then
  266. if (required == OptionRequired::Date && !time_style.is_undefined()) {
  267. // i. Throw a TypeError exception.
  268. return vm.throw_completion<TypeError>(ErrorType::IntlInvalidDateTimeFormatOption, "timeStyle"sv, "date"sv);
  269. }
  270. // c. If required is time and dateStyle is not undefined, then
  271. if (required == OptionRequired::Time && !date_style.is_undefined()) {
  272. // i. Throw a TypeError exception.
  273. return vm.throw_completion<TypeError>(ErrorType::IntlInvalidDateTimeFormatOption, "dateStyle"sv, "time"sv);
  274. }
  275. // d. Let styles be dataLocaleData.[[styles]].[[<resolvedCalendar>]].
  276. // e. Let bestFormat be DateTimeStyleFormat(dateStyle, timeStyle, styles).
  277. best_format = date_time_style_format(data_locale, date_time_format);
  278. }
  279. // 46. Else,
  280. else {
  281. // a. Let needDefaults be true.
  282. bool needs_defaults = true;
  283. // b. If required is date or any, then
  284. if (required == OptionRequired::Date || required == OptionRequired::Any) {
  285. // i. For each property name prop of « "weekday", "year", "month", "day" », do
  286. auto check_property_value = [&](auto const& value) {
  287. // 1. Let value be formatOptions.[[<prop>]].
  288. // 2. If value is not undefined, let needDefaults be false.
  289. if (value.has_value())
  290. needs_defaults = false;
  291. };
  292. check_property_value(format_options.weekday);
  293. check_property_value(format_options.year);
  294. check_property_value(format_options.month);
  295. check_property_value(format_options.day);
  296. }
  297. // c. If required is time or any, then
  298. if (required == OptionRequired::Time || required == OptionRequired::Any) {
  299. // i. For each property name prop of « "dayPeriod", "hour", "minute", "second", "fractionalSecondDigits" », do
  300. auto check_property_value = [&](auto const& value) {
  301. // 1. Let value be formatOptions.[[<prop>]].
  302. // 2. If value is not undefined, let needDefaults be false.
  303. if (value.has_value())
  304. needs_defaults = false;
  305. };
  306. check_property_value(format_options.day_period);
  307. check_property_value(format_options.hour);
  308. check_property_value(format_options.minute);
  309. check_property_value(format_options.second);
  310. check_property_value(format_options.fractional_second_digits);
  311. }
  312. // d. If needDefaults is true and defaults is either date or all, then
  313. if (needs_defaults && (defaults == OptionDefaults::Date || defaults == OptionDefaults::All)) {
  314. // i. For each property name prop of « "year", "month", "day" », do
  315. auto set_property_value = [&](auto& value) {
  316. // 1. Set formatOptions.[[<prop>]] to "numeric".
  317. value = ::Locale::CalendarPatternStyle::Numeric;
  318. };
  319. set_property_value(format_options.year);
  320. set_property_value(format_options.month);
  321. set_property_value(format_options.day);
  322. }
  323. // e. If needDefaults is true and defaults is either time or all, then
  324. if (needs_defaults && (defaults == OptionDefaults::Time || defaults == OptionDefaults::All)) {
  325. // i. For each property name prop of « "hour", "minute", "second" », do
  326. auto set_property_value = [&](auto& value) {
  327. // 1. Set formatOptions.[[<prop>]] to "numeric".
  328. value = ::Locale::CalendarPatternStyle::Numeric;
  329. };
  330. set_property_value(format_options.hour);
  331. set_property_value(format_options.minute);
  332. set_property_value(format_options.second);
  333. }
  334. // f. Let formats be dataLocaleData.[[formats]].[[<resolvedCalendar>]].
  335. auto formats = ::Locale::get_calendar_available_formats(data_locale, date_time_format->calendar());
  336. // g. If matcher is "basic", then
  337. if (matcher.as_string().utf8_string_view() == "basic"sv) {
  338. // i. Let bestFormat be BasicFormatMatcher(formatOptions, formats).
  339. best_format = basic_format_matcher(format_options, move(formats));
  340. }
  341. // h. Else,
  342. else {
  343. // i. Let bestFormat be BestFitFormatMatcher(formatOptions, formats).
  344. best_format = best_fit_format_matcher(format_options, move(formats));
  345. }
  346. }
  347. // 47. For each row in Table 6, except the header row, in table order, do
  348. date_time_format->for_each_calendar_field_zipped_with(*best_format, [&](auto& date_time_format_field, auto const& best_format_field, auto) {
  349. // a. Let prop be the name given in the Property column of the row.
  350. // b. If bestFormat has a field [[<prop>]], then
  351. if (best_format_field.has_value()) {
  352. // i. Let p be bestFormat.[[<prop>]].
  353. // ii. Set dateTimeFormat's internal slot whose name is the Internal Slot column of the row to p.
  354. date_time_format_field = best_format_field;
  355. }
  356. });
  357. String pattern;
  358. Vector<::Locale::CalendarRangePattern> range_patterns;
  359. // 48. If dateTimeFormat.[[Hour]] is undefined, then
  360. if (!date_time_format->has_hour()) {
  361. // a. Set dateTimeFormat.[[HourCycle]] to undefined.
  362. date_time_format->clear_hour_cycle();
  363. }
  364. // 49. If dateTimeFormat.[[HourCycle]] is "h11" or "h12", then
  365. if ((hour_cycle_value == ::Locale::HourCycle::H11) || (hour_cycle_value == ::Locale::HourCycle::H12)) {
  366. // a. Let pattern be bestFormat.[[pattern12]].
  367. if (best_format->pattern12.has_value()) {
  368. pattern = best_format->pattern12.release_value();
  369. } else {
  370. // Non-standard, LibUnicode only provides [[pattern12]] when [[pattern]] has a day
  371. // period. Other implementations provide [[pattern12]] as a copy of [[pattern]].
  372. pattern = move(best_format->pattern);
  373. }
  374. // b. Let rangePatterns be bestFormat.[[rangePatterns12]].
  375. range_patterns = ::Locale::get_calendar_range12_formats(data_locale, date_time_format->calendar(), best_format->skeleton);
  376. }
  377. // 50. Else,
  378. else {
  379. // a. Let pattern be bestFormat.[[pattern]].
  380. pattern = move(best_format->pattern);
  381. // b. Let rangePatterns be bestFormat.[[rangePatterns]].
  382. range_patterns = ::Locale::get_calendar_range_formats(data_locale, date_time_format->calendar(), best_format->skeleton);
  383. }
  384. // 51. Set dateTimeFormat.[[Pattern]] to pattern.
  385. date_time_format->set_pattern(move(pattern));
  386. // 52. Set dateTimeFormat.[[RangePatterns]] to rangePatterns.
  387. date_time_format->set_range_patterns(move(range_patterns));
  388. // 53. Return dateTimeFormat.
  389. return date_time_format;
  390. }
  391. // 11.1.3 FormatOffsetTimeZoneIdentifier ( offsetMinutes ), https://tc39.es/ecma402/#sec-formatoffsettimezoneidentifier
  392. String format_offset_time_zone_identifier(double offset_minutes)
  393. {
  394. // 1. If offsetMinutes ≥ 0, let sign be the code unit 0x002B (PLUS SIGN); otherwise, let sign be the code unit 0x002D (HYPHEN-MINUS).
  395. auto sign = offset_minutes >= 0.0 ? '+' : '-';
  396. // 2. Let absoluteMinutes be abs(offsetMinutes).
  397. auto absolute_minutes = fabs(offset_minutes);
  398. // 3. Let hours be floor(absoluteMinutes / 60).
  399. auto hours = static_cast<i64>(floor(absolute_minutes / 60.0));
  400. // 4. Let minutes be absoluteMinutes modulo 60.
  401. auto minutes = static_cast<i64>(modulo(absolute_minutes, 60.0));
  402. // 5. Return the string-concatenation of sign, ToZeroPaddedDecimalString(hours, 2), the code unit 0x003A (COLON), and ToZeroPaddedDecimalString(minutes, 2).
  403. return MUST(String::formatted("{}{:02}:{:02}", sign, hours, minutes));
  404. }
  405. }