PlainDate.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/Completion.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/PlainDateConstructor.h>
  15. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  16. #include <LibJS/Runtime/Temporal/PlainYearMonth.h>
  17. #include <LibJS/Runtime/Temporal/TimeZone.h>
  18. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  19. namespace JS::Temporal {
  20. // 3 Temporal.PlainDate Objects, https://tc39.es/proposal-temporal/#sec-temporal-plaindate-objects
  21. PlainDate::PlainDate(i32 year, u8 month, u8 day, Object& calendar, Object& prototype)
  22. : Object(prototype)
  23. , m_iso_year(year)
  24. , m_iso_month(month)
  25. , m_iso_day(day)
  26. , m_calendar(calendar)
  27. {
  28. }
  29. void PlainDate::visit_edges(Visitor& visitor)
  30. {
  31. Base::visit_edges(visitor);
  32. visitor.visit(&m_calendar);
  33. }
  34. // 3.5.1 CreateTemporalDate ( isoYear, isoMonth, isoDay, calendar [ , newTarget ] ), https://tc39.es/proposal-temporal/#sec-temporal-createtemporaldate
  35. ThrowCompletionOr<PlainDate*> create_temporal_date(GlobalObject& global_object, i32 iso_year, u8 iso_month, u8 iso_day, Object& calendar, FunctionObject const* new_target)
  36. {
  37. auto& vm = global_object.vm();
  38. // 1. Assert: isoYear is an integer.
  39. // 2. Assert: isoMonth is an integer.
  40. // 3. Assert: isoDay is an integer.
  41. // 4. Assert: Type(calendar) is Object.
  42. // 5. If ! IsValidISODate(isoYear, isoMonth, isoDay) is false, throw a RangeError exception.
  43. if (!is_valid_iso_date(iso_year, iso_month, iso_day))
  44. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate);
  45. // 6. If ! ISODateTimeWithinLimits(isoYear, isoMonth, isoDay, 12, 0, 0, 0, 0, 0) is false, throw a RangeError exception.
  46. if (!iso_date_time_within_limits(global_object, iso_year, iso_month, iso_day, 12, 0, 0, 0, 0, 0))
  47. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate);
  48. // 7. If newTarget is not present, set newTarget to %Temporal.PlainDate%.
  49. if (!new_target)
  50. new_target = global_object.temporal_plain_date_constructor();
  51. // 8. Let object be ? OrdinaryCreateFromConstructor(newTarget, "%Temporal.PlainDate.prototype%", « [[InitializedTemporalDate]], [[ISOYear]], [[ISOMonth]], [[ISODay]], [[Calendar]] »).
  52. // 9. Set object.[[ISOYear]] to isoYear.
  53. // 10. Set object.[[ISOMonth]] to isoMonth.
  54. // 11. Set object.[[ISODay]] to isoDay.
  55. // 12. Set object.[[Calendar]] to calendar.
  56. auto* object = TRY(ordinary_create_from_constructor<PlainDate>(global_object, *new_target, &GlobalObject::temporal_plain_date_prototype, iso_year, iso_month, iso_day, calendar));
  57. return object;
  58. }
  59. // 3.5.2 ToTemporalDate ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal-totemporaldate
  60. ThrowCompletionOr<PlainDate*> to_temporal_date(GlobalObject& global_object, Value item, Object* options)
  61. {
  62. auto& vm = global_object.vm();
  63. // 1. If options is not present, set options to undefined.
  64. // 2. Assert: Type(options) is Object or Undefined.
  65. // 3. If Type(item) is Object, then
  66. if (item.is_object()) {
  67. auto& item_object = item.as_object();
  68. // a. If item has an [[InitializedTemporalDate]] internal slot, then
  69. if (is<PlainDate>(item_object)) {
  70. // i. Return item.
  71. return static_cast<PlainDate*>(&item_object);
  72. }
  73. // b. If item has an [[InitializedTemporalZonedDateTime]] internal slot, then
  74. if (is<ZonedDateTime>(item_object)) {
  75. auto& zoned_date_time = static_cast<ZonedDateTime&>(item_object);
  76. // i. Let instant be ! CreateTemporalInstant(item.[[Nanoseconds]]).
  77. auto* instant = create_temporal_instant(global_object, zoned_date_time.nanoseconds()).release_value();
  78. // ii. Let plainDateTime be ? BuiltinTimeZoneGetPlainDateTimeFor(item.[[TimeZone]], instant, item.[[Calendar]]).
  79. auto* plain_date_time = TRY(builtin_time_zone_get_plain_date_time_for(global_object, &zoned_date_time.time_zone(), *instant, zoned_date_time.calendar()));
  80. // iii. Return ! CreateTemporalDate(plainDateTime.[[ISOYear]], plainDateTime.[[ISOMonth]], plainDateTime.[[ISODay]], plainDateTime.[[Calendar]]).
  81. return create_temporal_date(global_object, plain_date_time->iso_year(), plain_date_time->iso_month(), plain_date_time->iso_day(), plain_date_time->calendar());
  82. }
  83. // c. If item has an [[InitializedTemporalDateTime]] internal slot, then
  84. if (is<PlainDateTime>(item_object)) {
  85. auto& date_time_item = static_cast<PlainDateTime&>(item_object);
  86. // i. Return ! CreateTemporalDate(item.[[ISOYear]], item.[[ISOMonth]], item.[[ISODay]], item.[[Calendar]]).
  87. return create_temporal_date(global_object, date_time_item.iso_year(), date_time_item.iso_month(), date_time_item.iso_day(), date_time_item.calendar());
  88. }
  89. // d. Let calendar be ? GetTemporalCalendarWithISODefault(item).
  90. auto* calendar = TRY(get_temporal_calendar_with_iso_default(global_object, item_object));
  91. // e. Let fieldNames be ? CalendarFields(calendar, « "day", "month", "monthCode", "year" »).
  92. auto field_names = TRY(calendar_fields(global_object, *calendar, { "day"sv, "month"sv, "monthCode"sv, "year"sv }));
  93. // f. Let fields be ? PrepareTemporalFields(item, fieldNames, «»).
  94. auto* fields = TRY(prepare_temporal_fields(global_object, item_object, field_names, {}));
  95. // g. Return ? DateFromFields(calendar, fields, options).
  96. return date_from_fields(global_object, *calendar, *fields, options);
  97. }
  98. // 4. Perform ? ToTemporalOverflow(options).
  99. (void)TRY(to_temporal_overflow(global_object, options));
  100. // 5. Let string be ? ToString(item).
  101. auto string = TRY(item.to_string(global_object));
  102. // 6. Let result be ? ParseTemporalDateString(string).
  103. auto result = TRY(parse_temporal_date_string(global_object, string));
  104. // 7. Assert: ! IsValidISODate(result.[[Year]], result.[[Month]], result.[[Day]]) is true.
  105. VERIFY(is_valid_iso_date(result.year, result.month, result.day));
  106. // 8. Let calendar be ? ToTemporalCalendarWithISODefault(result.[[Calendar]]).
  107. auto* calendar = TRY(to_temporal_calendar_with_iso_default(global_object, result.calendar.has_value() ? js_string(vm, *result.calendar) : js_undefined()));
  108. // 9. Return ? CreateTemporalDate(result.[[Year]], result.[[Month]], result.[[Day]], calendar).
  109. return create_temporal_date(global_object, result.year, result.month, result.day, *calendar);
  110. }
  111. // 3.5.3 DifferenceISODate ( y1, m1, d1, y2, m2, d2, largestUnit ), https://tc39.es/proposal-temporal/#sec-temporal-differenceisodate
  112. DateDurationRecord difference_iso_date(GlobalObject& global_object, i32 year1, u8 month1, u8 day1, i32 year2, u8 month2, u8 day2, StringView largest_unit)
  113. {
  114. // 1. Assert: largestUnit is one of "year", "month", "week", or "day".
  115. VERIFY(largest_unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv));
  116. // 2. If largestUnit is "year" or "month", then
  117. if (largest_unit.is_one_of("year"sv, "month"sv)) {
  118. // a. Let sign be -(! CompareISODate(y1, m1, d1, y2, m2, d2)).
  119. auto sign = -compare_iso_date(year1, month1, day1, year2, month2, day2);
  120. // b. If sign is 0, return ! CreateDateDurationRecord(0, 0, 0, 0).
  121. if (sign == 0)
  122. return create_date_duration_record(0, 0, 0, 0);
  123. // c. Let start be the Record { [[Year]]: y1, [[Month]]: m1, [[Day]]: d1 }.
  124. auto start = ISODate { .year = year1, .month = month1, .day = day1 };
  125. // d. Let end be the Record { [[Year]]: y2, [[Month]]: m2, [[Day]]: d2 }.
  126. auto end = ISODate { .year = year2, .month = month2, .day = day2 };
  127. // e. Let years be end.[[Year]] − start.[[Year]].
  128. double years = end.year - start.year;
  129. // f. Let mid be ! AddISODate(y1, m1, d1, years, 0, 0, 0, "constrain").
  130. auto mid = MUST(add_iso_date(global_object, year1, month1, day1, years, 0, 0, 0, "constrain"sv));
  131. // g. Let midSign be -(! CompareISODate(mid.[[Year]], mid.[[Month]], mid.[[Day]], y2, m2, d2)).
  132. auto mid_sign = -compare_iso_date(mid.year, mid.month, mid.day, year2, month2, day2);
  133. // h. If midSign is 0, then
  134. if (mid_sign == 0) {
  135. // i. If largestUnit is "year", return ! CreateDateDurationRecord(years, 0, 0, 0).
  136. if (largest_unit == "year"sv)
  137. return create_date_duration_record(years, 0, 0, 0);
  138. // ii. Return ! CreateDateDurationRecord(0, years × 12, 0, 0).
  139. return create_date_duration_record(0, years * 12, 0, 0);
  140. }
  141. // i. Let months be end.[[Month]] − start.[[Month]].
  142. double months = end.month - start.month;
  143. // j. If midSign is not equal to sign, then
  144. if (mid_sign != sign) {
  145. // i. Set years to years - sign.
  146. years -= sign;
  147. // ii. Set months to months + sign × 12.
  148. months += sign * 12;
  149. }
  150. // k. Set mid to ! AddISODate(y1, m1, d1, years, months, 0, 0, "constrain").
  151. mid = MUST(add_iso_date(global_object, year1, month1, day1, years, months, 0, 0, "constrain"sv));
  152. // l. Set midSign to -(! CompareISODate(mid.[[Year]], mid.[[Month]], mid.[[Day]], y2, m2, d2)).
  153. mid_sign = -compare_iso_date(mid.year, mid.month, mid.day, year2, month2, day2);
  154. // m. If midSign is 0, then
  155. if (mid_sign == 0) {
  156. // i. If largestUnit is "year", return ! CreateDateDurationRecord(years, months, 0, 0).
  157. if (largest_unit == "year"sv)
  158. return create_date_duration_record(years, months, 0, 0);
  159. // ii. Return ! CreateDateDurationRecord(0, months + years × 12, 0, 0).
  160. return create_date_duration_record(0, months + years * 12, 0, 0);
  161. }
  162. // n. If midSign is not equal to sign, then
  163. if (mid_sign != sign) {
  164. // i. Set months to months - sign.
  165. months -= sign;
  166. // ii. If months is equal to -sign, then
  167. if (months == -sign) {
  168. // 1. Set years to years - sign.
  169. years -= sign;
  170. // 2. Set months to 11 × sign.
  171. months = 11 * sign;
  172. }
  173. // iii. Set mid to ! AddISODate(y1, m1, d1, years, months, 0, 0, "constrain").
  174. mid = MUST(add_iso_date(global_object, year1, month1, day1, years, months, 0, 0, "constrain"sv));
  175. }
  176. // o. Let days be 0.
  177. double days = 0;
  178. // p. If mid.[[Month]] = end.[[Month]], then
  179. if (mid.month == end.month) {
  180. // i. Assert: mid.[[Year]] = end.[[Year]].
  181. VERIFY(mid.year == end.year);
  182. // ii. Set days to end.[[Day]] - mid.[[Day]].
  183. days = end.day - mid.day;
  184. }
  185. // q. Else if sign < 0, set days to -mid.[[Day]] - (! ISODaysInMonth(end.[[Year]], end.[[Month]]) - end.[[Day]]).
  186. else if (sign < 0) {
  187. days = -mid.day - (iso_days_in_month(end.year, end.month) - end.day);
  188. }
  189. // r. Else, set days to end.[[Day]] + (! ISODaysInMonth(mid.[[Year]], mid.[[Month]]) - mid.[[Day]]).
  190. else {
  191. days = end.day + (iso_days_in_month(mid.year, mid.month) - mid.day);
  192. }
  193. // s. If largestUnit is "month", then
  194. if (largest_unit == "month"sv) {
  195. // i. Set months to months + years × 12.
  196. months += years * 12;
  197. // ii. Set years to 0.
  198. years = 0;
  199. }
  200. // t. Return ! CreateDateDurationRecord(years, months, 0, days).
  201. return create_date_duration_record(years, months, 0, days);
  202. }
  203. // 3. If largestUnit is "day" or "week", then
  204. else {
  205. ISODate smaller;
  206. ISODate greater;
  207. i8 sign;
  208. // a. If ! CompareISODate(y1, m1, d1, y2, m2, d2) < 0, then
  209. if (compare_iso_date(year1, month1, day1, year2, month2, day2) < 0) {
  210. // i. Let smaller be the Record { [[Year]]: y1, [[Month]]: m1, [[Day]]: d1 }.
  211. smaller = { .year = year1, .month = month1, .day = day1 };
  212. // ii. Let greater be the Record { [[Year]]: y2, [[Month]]: m2, [[Day]]: d2 }.
  213. greater = { .year = year2, .month = month2, .day = day2 };
  214. // iii. Let sign be 1.
  215. sign = 1;
  216. }
  217. // b. Else,
  218. else {
  219. // i. Let smaller be the Record { [[Year]]: y2, [[Month]]: m2, [[Day]]: d2 }.
  220. smaller = { .year = year2, .month = month2, .day = day2 };
  221. // ii. Let greater be the Record { [[Year]]: y1, [[Month]]: m1, [[Day]]: d1 }.
  222. greater = { .year = year1, .month = month1, .day = day1 };
  223. // iii. Let sign be −1.
  224. sign = -1;
  225. }
  226. // c. Let days be ! ToISODayOfYear(greater.[[Year]], greater.[[Month]], greater.[[Day]]) − ! ToISODayOfYear(smaller.[[Year]], smaller.[[Month]], smaller.[[Day]]).
  227. double days = to_iso_day_of_year(greater.year, greater.month, greater.day) - to_iso_day_of_year(smaller.year, smaller.month, smaller.day);
  228. // d. Let year be smaller.[[Year]].
  229. auto year = smaller.year;
  230. // e. Repeat, while year < greater.[[Year]],
  231. while (year < greater.year) {
  232. // i. Set days to days + ! ISODaysInYear(year).
  233. days += iso_days_in_year(year);
  234. // ii. Set year to year + 1.
  235. year++;
  236. }
  237. // f. Let weeks be 0.
  238. double weeks = 0;
  239. // g. If largestUnit is "week", then
  240. if (largest_unit == "week"sv) {
  241. // i. Set weeks to floor(days / 7).
  242. weeks = floor(days / 7);
  243. // ii. Set days to days modulo 7.
  244. days = fmod(days, 7);
  245. }
  246. // h. Return ! CreateDateDurationRecord(0, 0, weeks × sign, days × sign).
  247. // NOTE: We set weeks and days conditionally to avoid negative zero for 0 * -1.
  248. return create_date_duration_record(0, 0, (weeks != 0) ? weeks * sign : 0, (days != 0) ? days * sign : 0);
  249. }
  250. VERIFY_NOT_REACHED();
  251. }
  252. // 3.5.4 RegulateISODate ( year, month, day, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-regulateisodate
  253. ThrowCompletionOr<ISODate> regulate_iso_date(GlobalObject& global_object, double year, double month, double day, StringView overflow)
  254. {
  255. auto& vm = global_object.vm();
  256. // 1. Assert: year, month, and day are integers.
  257. VERIFY(year == trunc(year) && month == trunc(month) && day == trunc(day));
  258. // 2. Assert: overflow is either "constrain" or "reject".
  259. // NOTE: Asserted by the VERIFY_NOT_REACHED at the end
  260. // 3. If overflow is "reject", then
  261. if (overflow == "reject"sv) {
  262. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat these doubles as normal integers from this point onwards.
  263. // This does not change the exposed behavior as the call to IsValidISODate will immediately check that these values are valid ISO
  264. // values (for years: -273975 - 273975, for months: 1 - 12, for days: 1 - 31) all of which are subsets of this check.
  265. if (!AK::is_within_range<i32>(year) || !AK::is_within_range<u8>(month) || !AK::is_within_range<u8>(day))
  266. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate);
  267. auto y = static_cast<i32>(year);
  268. auto m = static_cast<u8>(month);
  269. auto d = static_cast<u8>(day);
  270. // a. If ! IsValidISODate(year, month, day) is false, throw a RangeError exception.
  271. if (!is_valid_iso_date(y, m, d))
  272. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate);
  273. // b. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day }.
  274. return ISODate { .year = y, .month = m, .day = d };
  275. }
  276. // 4. If overflow is "constrain", then
  277. else if (overflow == "constrain"sv) {
  278. // IMPLEMENTATION DEFINED: This is an optimization that allows us to treat this double as normal integer from this point onwards. This
  279. // does not change the exposed behavior as the parent's call to CreateTemporalDate will immediately check that this value is a valid
  280. // ISO value for years: -273975 - 273975, which is a subset of this check.
  281. if (!AK::is_within_range<i32>(year))
  282. return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidPlainDate);
  283. auto y = static_cast<i32>(year);
  284. // a. Set month to the result of clamping month between 1 and 12.
  285. month = clamp(month, 1, 12);
  286. // b. Let daysInMonth be ! ISODaysInMonth(year, month).
  287. auto days_in_month = iso_days_in_month(y, (u8)month);
  288. // c. Set day to the result of clamping day between 1 and daysInMonth.
  289. day = clamp(day, 1, days_in_month);
  290. // d. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day }.
  291. return ISODate { .year = y, .month = static_cast<u8>(month), .day = static_cast<u8>(day) };
  292. }
  293. VERIFY_NOT_REACHED();
  294. }
  295. // 3.5.5 IsValidISODate ( year, month, day ), https://tc39.es/proposal-temporal/#sec-temporal-isvalidisodate
  296. bool is_valid_iso_date(i32 year, u8 month, u8 day)
  297. {
  298. // 1. Assert: year, month, and day are integers.
  299. // 2. If month < 1 or month > 12, then
  300. if (month < 1 || month > 12) {
  301. // a. Return false.
  302. return false;
  303. }
  304. // 3. Let daysInMonth be ! ISODaysInMonth(year, month).
  305. auto days_in_month = iso_days_in_month(year, month);
  306. // 4. If day < 1 or day > daysInMonth, then
  307. if (day < 1 || day > days_in_month) {
  308. // a. Return false.
  309. return false;
  310. }
  311. // 5. Return true.
  312. return true;
  313. }
  314. // 3.5.6 BalanceISODate ( year, month, day ), https://tc39.es/proposal-temporal/#sec-temporal-balanceisodate
  315. ISODate balance_iso_date(double year_, double month_, double day)
  316. {
  317. // 1. Assert: year, month, and day are integers.
  318. // 2. Let balancedYearMonth be ! BalanceISOYearMonth(year, month).
  319. auto balanced_year_month = balance_iso_year_month(year_, month_);
  320. // 3. Set month to balancedYearMonth.[[Month]].
  321. auto month = balanced_year_month.month;
  322. // 4. Set year to balancedYearMonth.[[Year]].
  323. auto year = balanced_year_month.year;
  324. // 5. NOTE: To deal with negative numbers of days whose absolute value is greater than the number of days in a year, the following section subtracts years and adds days until the number of days is greater than −366 or −365.
  325. i32 test_year;
  326. // 6. If month > 2, then
  327. if (month > 2) {
  328. // a. Let testYear be year.
  329. test_year = year;
  330. }
  331. // 7. Else,
  332. else {
  333. // a. Let testYear be year − 1.
  334. test_year = year - 1;
  335. }
  336. // 8. Repeat, while day < −1 × ! ISODaysInYear(testYear),
  337. while (day < -1 * iso_days_in_year(test_year)) {
  338. // a. Set day to day + !ISODaysInYear(testYear).
  339. day += iso_days_in_year(test_year);
  340. // b. Set year to year − 1.
  341. year--;
  342. // c. Set testYear to testYear − 1.
  343. test_year--;
  344. }
  345. // 9. NOTE: To deal with numbers of days greater than the number of days in a year, the following section adds years and subtracts days until the number of days is less than 366 or 365.
  346. // 10. Set testYear to testYear + 1.
  347. test_year++;
  348. // 11. Repeat, while day > ! ISODaysInYear(testYear),
  349. while (day > iso_days_in_year(test_year)) {
  350. // a. Set day to day − ! ISODaysInYear(testYear).
  351. day -= iso_days_in_year(test_year);
  352. // b. Set year to year + 1.
  353. year++;
  354. // c. Set testYear to testYear + 1.
  355. test_year++;
  356. }
  357. // 12. NOTE: To deal with negative numbers of days whose absolute value is greater than the number of days in the current month, the following section subtracts months and adds days until the number of days is greater than 0.
  358. // 13. Repeat, while day < 1,
  359. while (day < 1) {
  360. // a. Set balancedYearMonth to ! BalanceISOYearMonth(year, month − 1).
  361. balanced_year_month = balance_iso_year_month(year, month - 1);
  362. // b. Set year to balancedYearMonth.[[Year]].
  363. year = balanced_year_month.year;
  364. // c. Set month to balancedYearMonth.[[Month]].
  365. month = balanced_year_month.month;
  366. // d. Set day to day + ! ISODaysInMonth(year, month).
  367. day += iso_days_in_month(year, month);
  368. }
  369. // 14. NOTE: To deal with numbers of days greater than the number of days in the current month, the following section adds months and subtracts days until the number of days is less than the number of days in the month.
  370. // 15. Repeat, while day > ! ISODaysInMonth(year, month),
  371. while (day > iso_days_in_month(year, month)) {
  372. // a. Set day to day − ! ISODaysInMonth(year, month).
  373. day -= iso_days_in_month(year, month);
  374. // b. Set balancedYearMonth to ! BalanceISOYearMonth(year, month + 1).
  375. balanced_year_month = balance_iso_year_month(year, month + 1);
  376. // c. Set year to balancedYearMonth.[[Year]].
  377. year = balanced_year_month.year;
  378. // d. Set month to balancedYearMonth.[[Month]].
  379. month = balanced_year_month.month;
  380. }
  381. // 16. Return the Record { [[Year]]: year, [[Month]]: month, [[Day]]: day }.
  382. return ISODate { .year = year, .month = static_cast<u8>(month), .day = static_cast<u8>(day) };
  383. }
  384. // 3.5.7 PadISOYear ( y ), https://tc39.es/proposal-temporal/#sec-temporal-padisoyear
  385. String pad_iso_year(i32 y)
  386. {
  387. // 1. Assert: y is an integer.
  388. // 2. If y ≥ 0 and y ≤ 9999, then
  389. if (y >= 0 && y <= 9999) {
  390. // a. Return y formatted as a four-digit decimal number, padded to the left with zeroes as necessary.
  391. return String::formatted("{:04}", y);
  392. }
  393. // 3. If y > 0, let yearSign be "+"; otherwise, let yearSign be "-".
  394. auto year_sign = y > 0 ? '+' : '-';
  395. // 4. Let year be abs(y), formatted as a six-digit decimal number, padded to the left with zeroes as necessary.
  396. // 5. Return the string-concatenation of yearSign and year.
  397. return String::formatted("{}{:06}", year_sign, abs(y));
  398. }
  399. // 3.5.8 TemporalDateToString ( temporalDate, showCalendar ), https://tc39.es/proposal-temporal/#sec-temporal-temporaldatetostring
  400. ThrowCompletionOr<String> temporal_date_to_string(GlobalObject& global_object, PlainDate& temporal_date, StringView show_calendar)
  401. {
  402. // 1. Assert: Type(temporalDate) is Object.
  403. // 2. Assert: temporalDate has an [[InitializedTemporalDate]] internal slot.
  404. // 3. Let year be ! PadISOYear(temporalDate.[[ISOYear]]).
  405. auto year = pad_iso_year(temporal_date.iso_year());
  406. // 4. Let month be temporalDate.[[ISOMonth]] formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  407. auto month = String::formatted("{:02}", temporal_date.iso_month());
  408. // 5. Let day be temporalDate.[[ISODay]] formatted as a two-digit decimal number, padded to the left with a zero if necessary.
  409. auto day = String::formatted("{:02}", temporal_date.iso_day());
  410. // 6. Let calendarID be ? ToString(temporalDate.[[Calendar]]).
  411. auto calendar_id = TRY(Value(&temporal_date.calendar()).to_string(global_object));
  412. // 7. Let calendar be ! FormatCalendarAnnotation(calendarID, showCalendar).
  413. auto calendar = format_calendar_annotation(calendar_id, show_calendar);
  414. // 8. Return the string-concatenation of year, the code unit 0x002D (HYPHEN-MINUS), month, the code unit 0x002D (HYPHEN-MINUS), day, and calendar.
  415. return String::formatted("{}-{}-{}{}", year, month, day, calendar);
  416. }
  417. // 3.5.9 AddISODate ( year, month, day, years, months, weeks, days, overflow ), https://tc39.es/proposal-temporal/#sec-temporal-addisodate
  418. ThrowCompletionOr<ISODate> add_iso_date(GlobalObject& global_object, i32 year, u8 month, u8 day, double years, double months, double weeks, double days, StringView overflow)
  419. {
  420. // 1. Assert: year, month, day, years, months, weeks, and days are integers.
  421. VERIFY(years == trunc(years) && months == trunc(months) && weeks == trunc(weeks) && days == trunc(days));
  422. // 2. Assert: overflow is either "constrain" or "reject".
  423. VERIFY(overflow == "constrain"sv || overflow == "reject"sv);
  424. // 3. Let intermediate be ! BalanceISOYearMonth(year + years, month + months).
  425. auto intermediate_year_month = balance_iso_year_month(year + years, month + months);
  426. // 4. Let intermediate be ? RegulateISODate(intermediate.[[Year]], intermediate.[[Month]], day, overflow).
  427. auto intermediate_date = TRY(regulate_iso_date(global_object, intermediate_year_month.year, intermediate_year_month.month, day, overflow));
  428. // 5. Set days to days + 7 × weeks.
  429. days += 7 * weeks;
  430. // 6. Let d be intermediate.[[Day]] + days.
  431. auto d = intermediate_date.day + days;
  432. // 7. Let intermediate be ! BalanceISODate(intermediate.[[Year]], intermediate.[[Month]], d).
  433. auto intermediate = balance_iso_date(intermediate_date.year, intermediate_date.month, d);
  434. // 8. Return ? RegulateISODate(intermediate.[[Year]], intermediate.[[Month]], intermediate.[[Day]], overflow).
  435. return regulate_iso_date(global_object, intermediate.year, intermediate.month, intermediate.day, overflow);
  436. }
  437. // 3.5.10 CompareISODate ( y1, m1, d1, y2, m2, d2 ), https://tc39.es/proposal-temporal/#sec-temporal-compareisodate
  438. i8 compare_iso_date(i32 year1, u8 month1, u8 day1, i32 year2, u8 month2, u8 day2)
  439. {
  440. // 1. Assert: y1, m1, d1, y2, m2, and d2 are integers.
  441. // 2. If y1 > y2, return 1.
  442. if (year1 > year2)
  443. return 1;
  444. // 3. If y1 < y2, return -1.
  445. if (year1 < year2)
  446. return -1;
  447. // 4. If m1 > m2, return 1.
  448. if (month1 > month2)
  449. return 1;
  450. // 5. If m1 < m2, return -1.
  451. if (month1 < month2)
  452. return -1;
  453. // 6. If d1 > d2, return 1.
  454. if (day1 > day2)
  455. return 1;
  456. // 7. If d1 < d2, return -1.
  457. if (day1 < day2)
  458. return -1;
  459. // 8. Return 0.
  460. return 0;
  461. }
  462. }