Date.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. /*
  2. * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2022-2023, Tim Flynn <trflynn89@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/NumericLimits.h>
  8. #include <AK/StringBuilder.h>
  9. #include <AK/Time.h>
  10. #include <LibJS/Runtime/AbstractOperations.h>
  11. #include <LibJS/Runtime/Date.h>
  12. #include <LibJS/Runtime/GlobalObject.h>
  13. #include <LibJS/Runtime/Temporal/ISO8601.h>
  14. #include <LibTimeZone/TimeZone.h>
  15. #include <time.h>
  16. namespace JS {
  17. JS_DEFINE_ALLOCATOR(Date);
  18. static Crypto::SignedBigInteger const s_one_billion_bigint { 1'000'000'000 };
  19. static Crypto::SignedBigInteger const s_one_million_bigint { 1'000'000 };
  20. static Crypto::SignedBigInteger const s_one_thousand_bigint { 1'000 };
  21. Crypto::SignedBigInteger const ns_per_day_bigint { static_cast<i64>(ns_per_day) };
  22. NonnullGCPtr<Date> Date::create(Realm& realm, double date_value)
  23. {
  24. return realm.heap().allocate<Date>(realm, date_value, realm.intrinsics().date_prototype());
  25. }
  26. Date::Date(double date_value, Object& prototype)
  27. : Object(ConstructWithPrototypeTag::Tag, prototype)
  28. , m_date_value(date_value)
  29. {
  30. }
  31. Date::~Date() = default;
  32. ErrorOr<String> Date::iso_date_string() const
  33. {
  34. int year = year_from_time(m_date_value);
  35. StringBuilder builder;
  36. if (year < 0)
  37. builder.appendff("-{:06}", -year);
  38. else if (year > 9999)
  39. builder.appendff("+{:06}", year);
  40. else
  41. builder.appendff("{:04}", year);
  42. builder.append('-');
  43. builder.appendff("{:02}", month_from_time(m_date_value) + 1);
  44. builder.append('-');
  45. builder.appendff("{:02}", date_from_time(m_date_value));
  46. builder.append('T');
  47. builder.appendff("{:02}", hour_from_time(m_date_value));
  48. builder.append(':');
  49. builder.appendff("{:02}", min_from_time(m_date_value));
  50. builder.append(':');
  51. builder.appendff("{:02}", sec_from_time(m_date_value));
  52. builder.append('.');
  53. builder.appendff("{:03}", ms_from_time(m_date_value));
  54. builder.append('Z');
  55. return builder.to_string();
  56. }
  57. // 21.4.1.3 Day ( t ), https://tc39.es/ecma262/#sec-day
  58. double day(double time_value)
  59. {
  60. // 1. Return ๐”ฝ(floor(โ„(t / msPerDay))).
  61. return floor(time_value / ms_per_day);
  62. }
  63. // 21.4.1.4 TimeWithinDay ( t ), https://tc39.es/ecma262/#sec-timewithinday
  64. double time_within_day(double time)
  65. {
  66. // 1. Return ๐”ฝ(โ„(t) modulo โ„(msPerDay)).
  67. return modulo(time, ms_per_day);
  68. }
  69. // 21.4.1.5 DaysInYear ( y ), https://tc39.es/ecma262/#sec-daysinyear
  70. u16 days_in_year(i32 y)
  71. {
  72. // 1. Let ry be โ„(y).
  73. auto ry = static_cast<double>(y);
  74. // 2. If (ry modulo 400) = 0, return 366๐”ฝ.
  75. if (modulo(ry, 400.0) == 0)
  76. return 366;
  77. // 3. If (ry modulo 100) = 0, return 365๐”ฝ.
  78. if (modulo(ry, 100.0) == 0)
  79. return 365;
  80. // 4. If (ry modulo 4) = 0, return 366๐”ฝ.
  81. if (modulo(ry, 4.0) == 0)
  82. return 366;
  83. // 5. Return 365๐”ฝ.
  84. return 365;
  85. }
  86. // 21.4.1.6 DayFromYear ( y ), https://tc39.es/ecma262/#sec-dayfromyear
  87. double day_from_year(i32 y)
  88. {
  89. // 1. Let ry be โ„(y).
  90. auto ry = static_cast<double>(y);
  91. // 2. NOTE: In the following steps, each _numYearsN_ is the number of years divisible by N that occur between the
  92. // epoch and the start of year y. (The number is negative if y is before the epoch.)
  93. // 3. Let numYears1 be (ry - 1970).
  94. auto num_years_1 = ry - 1970;
  95. // 4. Let numYears4 be floor((ry - 1969) / 4).
  96. auto num_years_4 = floor((ry - 1969) / 4.0);
  97. // 5. Let numYears100 be floor((ry - 1901) / 100).
  98. auto num_years_100 = floor((ry - 1901) / 100.0);
  99. // 6. Let numYears400 be floor((ry - 1601) / 400).
  100. auto num_years_400 = floor((ry - 1601) / 400.0);
  101. // 7. Return ๐”ฝ(365 ร— numYears1 + numYears4 - numYears100 + numYears400).
  102. return 365.0 * num_years_1 + num_years_4 - num_years_100 + num_years_400;
  103. }
  104. // 21.4.1.7 TimeFromYear ( y ), https://tc39.es/ecma262/#sec-timefromyear
  105. double time_from_year(i32 y)
  106. {
  107. // 1. Return msPerDay ร— DayFromYear(y).
  108. return ms_per_day * day_from_year(y);
  109. }
  110. // 21.4.1.8 YearFromTime ( t ), https://tc39.es/ecma262/#sec-yearfromtime
  111. i32 year_from_time(double t)
  112. {
  113. // 1. Return the largest integral Number y (closest to +โˆž) such that TimeFromYear(y) โ‰ค t.
  114. if (!Value(t).is_finite_number())
  115. return NumericLimits<i32>::max();
  116. // Approximation using average number of milliseconds per year. We might have to adjust this guess afterwards.
  117. auto year = static_cast<i32>(floor(t / (365.2425 * ms_per_day) + 1970));
  118. auto year_t = time_from_year(year);
  119. if (year_t > t)
  120. year--;
  121. else if (year_t + days_in_year(year) * ms_per_day <= t)
  122. year++;
  123. return year;
  124. }
  125. // 21.4.1.9 DayWithinYear ( t ), https://tc39.es/ecma262/#sec-daywithinyear
  126. u16 day_within_year(double t)
  127. {
  128. if (!Value(t).is_finite_number())
  129. return 0;
  130. // 1. Return Day(t) - DayFromYear(YearFromTime(t)).
  131. return static_cast<u16>(day(t) - day_from_year(year_from_time(t)));
  132. }
  133. // 21.4.1.10 InLeapYear ( t ), https://tc39.es/ecma262/#sec-inleapyear
  134. bool in_leap_year(double t)
  135. {
  136. // 1. If DaysInYear(YearFromTime(t)) is 366๐”ฝ, return 1๐”ฝ; else return +0๐”ฝ.
  137. return days_in_year(year_from_time(t)) == 366;
  138. }
  139. // 21.4.1.11 MonthFromTime ( t ), https://tc39.es/ecma262/#sec-monthfromtime
  140. u8 month_from_time(double t)
  141. {
  142. // 1. Let inLeapYear be InLeapYear(t).
  143. auto in_leap_year = static_cast<unsigned>(JS::in_leap_year(t));
  144. // 2. Let dayWithinYear be DayWithinYear(t).
  145. auto day_within_year = JS::day_within_year(t);
  146. // 3. If dayWithinYear < 31๐”ฝ, return +0๐”ฝ.
  147. if (day_within_year < 31)
  148. return 0;
  149. // 4. If dayWithinYear < 59๐”ฝ + inLeapYear, return 1๐”ฝ.
  150. if (day_within_year < (59 + in_leap_year))
  151. return 1;
  152. // 5. If dayWithinYear < 90๐”ฝ + inLeapYear, return 2๐”ฝ.
  153. if (day_within_year < (90 + in_leap_year))
  154. return 2;
  155. // 6. If dayWithinYear < 120๐”ฝ + inLeapYear, return 3๐”ฝ.
  156. if (day_within_year < (120 + in_leap_year))
  157. return 3;
  158. // 7. If dayWithinYear < 151๐”ฝ + inLeapYear, return 4๐”ฝ.
  159. if (day_within_year < (151 + in_leap_year))
  160. return 4;
  161. // 8. If dayWithinYear < 181๐”ฝ + inLeapYear, return 5๐”ฝ.
  162. if (day_within_year < (181 + in_leap_year))
  163. return 5;
  164. // 9. If dayWithinYear < 212๐”ฝ + inLeapYear, return 6๐”ฝ.
  165. if (day_within_year < (212 + in_leap_year))
  166. return 6;
  167. // 10. If dayWithinYear < 243๐”ฝ + inLeapYear, return 7๐”ฝ.
  168. if (day_within_year < (243 + in_leap_year))
  169. return 7;
  170. // 11. If dayWithinYear < 273๐”ฝ + inLeapYear, return 8๐”ฝ.
  171. if (day_within_year < (273 + in_leap_year))
  172. return 8;
  173. // 12. If dayWithinYear < 304๐”ฝ + inLeapYear, return 9๐”ฝ.
  174. if (day_within_year < (304 + in_leap_year))
  175. return 9;
  176. // 13. If dayWithinYear < 334๐”ฝ + inLeapYear, return 10๐”ฝ.
  177. if (day_within_year < (334 + in_leap_year))
  178. return 10;
  179. // 14. Assert: dayWithinYear < 365๐”ฝ + inLeapYear.
  180. VERIFY(day_within_year < (365 + in_leap_year));
  181. // 15. Return 11๐”ฝ.
  182. return 11;
  183. }
  184. // 21.4.1.12 DateFromTime ( t ), https://tc39.es/ecma262/#sec-datefromtime
  185. u8 date_from_time(double t)
  186. {
  187. // 1. Let inLeapYear be InLeapYear(t).
  188. auto in_leap_year = static_cast<unsigned>(JS::in_leap_year(t));
  189. // 2. Let dayWithinYear be DayWithinYear(t).
  190. auto day_within_year = JS::day_within_year(t);
  191. // 3. Let month be MonthFromTime(t).
  192. auto month = month_from_time(t);
  193. // 4. If month is +0๐”ฝ, return dayWithinYear + 1๐”ฝ.
  194. if (month == 0)
  195. return day_within_year + 1;
  196. // 5. If month is 1๐”ฝ, return dayWithinYear - 30๐”ฝ.
  197. if (month == 1)
  198. return day_within_year - 30;
  199. // 6. If month is 2๐”ฝ, return dayWithinYear - 58๐”ฝ - inLeapYear.
  200. if (month == 2)
  201. return day_within_year - 58 - in_leap_year;
  202. // 7. If month is 3๐”ฝ, return dayWithinYear - 89๐”ฝ - inLeapYear.
  203. if (month == 3)
  204. return day_within_year - 89 - in_leap_year;
  205. // 8. If month is 4๐”ฝ, return dayWithinYear - 119๐”ฝ - inLeapYear.
  206. if (month == 4)
  207. return day_within_year - 119 - in_leap_year;
  208. // 9. If month is 5๐”ฝ, return dayWithinYear - 150๐”ฝ - inLeapYear.
  209. if (month == 5)
  210. return day_within_year - 150 - in_leap_year;
  211. // 10. If month is 6๐”ฝ, return dayWithinYear - 180๐”ฝ - inLeapYear.
  212. if (month == 6)
  213. return day_within_year - 180 - in_leap_year;
  214. // 11. If month is 7๐”ฝ, return dayWithinYear - 211๐”ฝ - inLeapYear.
  215. if (month == 7)
  216. return day_within_year - 211 - in_leap_year;
  217. // 12. If month is 8๐”ฝ, return dayWithinYear - 242๐”ฝ - inLeapYear.
  218. if (month == 8)
  219. return day_within_year - 242 - in_leap_year;
  220. // 13. If month is 9๐”ฝ, return dayWithinYear - 272๐”ฝ - inLeapYear.
  221. if (month == 9)
  222. return day_within_year - 272 - in_leap_year;
  223. // 14. If month is 10๐”ฝ, return dayWithinYear - 303๐”ฝ - inLeapYear.
  224. if (month == 10)
  225. return day_within_year - 303 - in_leap_year;
  226. // 15. Assert: month is 11๐”ฝ.
  227. VERIFY(month == 11);
  228. // 16. Return dayWithinYear - 333๐”ฝ - inLeapYear.
  229. return day_within_year - 333 - in_leap_year;
  230. }
  231. // 21.4.1.13 WeekDay ( t ), https://tc39.es/ecma262/#sec-weekday
  232. u8 week_day(double t)
  233. {
  234. if (!Value(t).is_finite_number())
  235. return 0;
  236. // 1. Return ๐”ฝ(โ„(Day(t) + 4๐”ฝ) modulo 7).
  237. return static_cast<u8>(modulo(day(t) + 4, 7));
  238. }
  239. // 21.4.1.14 HourFromTime ( t ), https://tc39.es/ecma262/#sec-hourfromtime
  240. u8 hour_from_time(double t)
  241. {
  242. if (!Value(t).is_finite_number())
  243. return 0;
  244. // 1. Return ๐”ฝ(floor(โ„(t / msPerHour)) modulo HoursPerDay).
  245. return static_cast<u8>(modulo(floor(t / ms_per_hour), hours_per_day));
  246. }
  247. // 21.4.1.15 MinFromTime ( t ), https://tc39.es/ecma262/#sec-minfromtime
  248. u8 min_from_time(double t)
  249. {
  250. if (!Value(t).is_finite_number())
  251. return 0;
  252. // 1. Return ๐”ฝ(floor(โ„(t / msPerMinute)) modulo MinutesPerHour).
  253. return static_cast<u8>(modulo(floor(t / ms_per_minute), minutes_per_hour));
  254. }
  255. // 21.4.1.16 SecFromTime ( t ), https://tc39.es/ecma262/#sec-secfromtime
  256. u8 sec_from_time(double t)
  257. {
  258. if (!Value(t).is_finite_number())
  259. return 0;
  260. // 1. Return ๐”ฝ(floor(โ„(t / msPerSecond)) modulo SecondsPerMinute).
  261. return static_cast<u8>(modulo(floor(t / ms_per_second), seconds_per_minute));
  262. }
  263. // 21.4.1.17 msFromTime ( t ), https://tc39.es/ecma262/#sec-msfromtime
  264. u16 ms_from_time(double t)
  265. {
  266. if (!Value(t).is_finite_number())
  267. return 0;
  268. // 1. Return ๐”ฝ(โ„(t) modulo โ„(msPerSecond)).
  269. return static_cast<u16>(modulo(t, ms_per_second));
  270. }
  271. // 21.4.1.18 GetUTCEpochNanoseconds ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/ecma262/#sec-getutcepochnanoseconds
  272. Crypto::SignedBigInteger get_utc_epoch_nanoseconds(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond)
  273. {
  274. // 1. Let date be MakeDay(๐”ฝ(year), ๐”ฝ(month - 1), ๐”ฝ(day)).
  275. auto date = make_day(year, month - 1, day);
  276. // 2. Let time be MakeTime(๐”ฝ(hour), ๐”ฝ(minute), ๐”ฝ(second), ๐”ฝ(millisecond)).
  277. auto time = make_time(hour, minute, second, millisecond);
  278. // 3. Let ms be MakeDate(date, time).
  279. auto ms = make_date(date, time);
  280. // 4. Assert: ms is an integral Number.
  281. VERIFY(ms == trunc(ms));
  282. // 5. Return โ„ค(โ„(ms) ร— 10^6 + microsecond ร— 10^3 + nanosecond).
  283. auto result = Crypto::SignedBigInteger { ms }.multiplied_by(s_one_million_bigint);
  284. result = result.plus(Crypto::SignedBigInteger { static_cast<i32>(microsecond) }.multiplied_by(s_one_thousand_bigint));
  285. result = result.plus(Crypto::SignedBigInteger { static_cast<i32>(nanosecond) });
  286. return result;
  287. }
  288. static i64 clip_bigint_to_sane_time(Crypto::SignedBigInteger const& value)
  289. {
  290. static Crypto::SignedBigInteger const min_bigint { NumericLimits<i64>::min() };
  291. static Crypto::SignedBigInteger const max_bigint { NumericLimits<i64>::max() };
  292. // The provided epoch (nano)seconds value is potentially out of range for AK::Duration and subsequently
  293. // get_time_zone_offset(). We can safely assume that the TZDB has no useful information that far
  294. // into the past and future anyway, so clamp it to the i64 range.
  295. if (value < min_bigint)
  296. return NumericLimits<i64>::min();
  297. if (value > max_bigint)
  298. return NumericLimits<i64>::max();
  299. // FIXME: Can we do this without string conversion?
  300. return value.to_base_deprecated(10).to_number<i64>().value();
  301. }
  302. // 21.4.1.20 GetNamedTimeZoneEpochNanoseconds ( timeZoneIdentifier, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/ecma262/#sec-getnamedtimezoneepochnanoseconds
  303. Vector<Crypto::SignedBigInteger> get_named_time_zone_epoch_nanoseconds(StringView time_zone_identifier, i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond)
  304. {
  305. auto local_nanoseconds = get_utc_epoch_nanoseconds(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond);
  306. auto local_time = UnixDateTime::from_nanoseconds_since_epoch(clip_bigint_to_sane_time(local_nanoseconds));
  307. // FIXME: LibTimeZone does not behave exactly as the spec expects. It does not consider repeated or skipped time points.
  308. auto offset = TimeZone::get_time_zone_offset(time_zone_identifier, local_time);
  309. // Can only fail if the time zone identifier is invalid, which cannot be the case here.
  310. VERIFY(offset.has_value());
  311. return { local_nanoseconds.minus(Crypto::SignedBigInteger { offset->seconds }.multiplied_by(s_one_billion_bigint)) };
  312. }
  313. // 21.4.1.21 GetNamedTimeZoneOffsetNanoseconds ( timeZoneIdentifier, epochNanoseconds ), https://tc39.es/ecma262/#sec-getnamedtimezoneoffsetnanoseconds
  314. i64 get_named_time_zone_offset_nanoseconds(StringView time_zone_identifier, Crypto::SignedBigInteger const& epoch_nanoseconds)
  315. {
  316. // Only called with validated time zone identifier as argument.
  317. auto time_zone = TimeZone::time_zone_from_string(time_zone_identifier);
  318. VERIFY(time_zone.has_value());
  319. // Since UnixDateTime::from_seconds_since_epoch() and UnixDateTime::from_nanoseconds_since_epoch() both take an i64, converting to
  320. // seconds first gives us a greater range. The TZDB doesn't have sub-second offsets.
  321. auto seconds = epoch_nanoseconds.divided_by(s_one_billion_bigint).quotient;
  322. auto time = UnixDateTime::from_seconds_since_epoch(clip_bigint_to_sane_time(seconds));
  323. auto offset = TimeZone::get_time_zone_offset(*time_zone, time);
  324. VERIFY(offset.has_value());
  325. return offset->seconds * 1'000'000'000;
  326. }
  327. // 21.4.1.23 AvailableNamedTimeZoneIdentifiers ( ), https://tc39.es/ecma262/#sec-time-zone-identifier-record
  328. Vector<TimeZoneIdentifier> available_named_time_zone_identifiers()
  329. {
  330. // 1. If the implementation does not include local political rules for any time zones, then
  331. // a. Return ยซ the Time Zone Identifier Record { [[Identifier]]: "UTC", [[PrimaryIdentifier]]: "UTC" } ยป.
  332. // NOTE: This step is not applicable as LibTimeZone will always return at least UTC, even if the TZDB is disabled.
  333. // 2. Let identifiers be the List of unique available named time zone identifiers.
  334. auto identifiers = TimeZone::all_time_zones();
  335. // 3. Sort identifiers into the same order as if an Array of the same values had been sorted using %Array.prototype.sort% with undefined as comparefn.
  336. // NOTE: LibTimeZone provides the identifiers already sorted.
  337. // 4. Let result be a new empty List.
  338. Vector<TimeZoneIdentifier> result;
  339. result.ensure_capacity(identifiers.size());
  340. bool found_utc = false;
  341. // 5. For each element identifier of identifiers, do
  342. for (auto identifier : identifiers) {
  343. // a. Let primary be identifier.
  344. auto primary = identifier.name;
  345. // b. If identifier is a non-primary time zone identifier in this implementation and identifier is not "UTC", then
  346. if (identifier.is_link == TimeZone::IsLink::Yes && identifier.name != "UTC"sv) {
  347. // i. Set primary to the primary time zone identifier associated with identifier.
  348. // ii. NOTE: An implementation may need to resolve identifier iteratively to obtain the primary time zone identifier.
  349. primary = TimeZone::canonicalize_time_zone(identifier.name).value();
  350. }
  351. // c. Let record be the Time Zone Identifier Record { [[Identifier]]: identifier, [[PrimaryIdentifier]]: primary }.
  352. TimeZoneIdentifier record { .identifier = identifier.name, .primary_identifier = primary };
  353. // d. Append record to result.
  354. result.unchecked_append(record);
  355. if (!found_utc && identifier.name == "UTC"sv && primary == "UTC"sv)
  356. found_utc = true;
  357. }
  358. // 6. Assert: result contains a Time Zone Identifier Record r such that r.[[Identifier]] is "UTC" and r.[[PrimaryIdentifier]] is "UTC".
  359. VERIFY(found_utc);
  360. // 7. Return result.
  361. return result;
  362. }
  363. // 21.4.1.24 SystemTimeZoneIdentifier ( ), https://tc39.es/ecma262/#sec-systemtimezoneidentifier
  364. StringView system_time_zone_identifier()
  365. {
  366. return TimeZone::current_time_zone();
  367. }
  368. // 21.4.1.25 LocalTime ( t ), https://tc39.es/ecma262/#sec-localtime
  369. double local_time(double time)
  370. {
  371. // 1. Let systemTimeZoneIdentifier be SystemTimeZoneIdentifier().
  372. auto system_time_zone_identifier = JS::system_time_zone_identifier();
  373. double offset_nanoseconds { 0 };
  374. // 2. If IsTimeZoneOffsetString(systemTimeZoneIdentifier) is true, then
  375. if (is_time_zone_offset_string(system_time_zone_identifier)) {
  376. // a. Let offsetNs be ParseTimeZoneOffsetString(systemTimeZoneIdentifier).
  377. offset_nanoseconds = parse_time_zone_offset_string(system_time_zone_identifier);
  378. }
  379. // 3. Else,
  380. else {
  381. // a. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, โ„ค(โ„(t) ร— 10^6)).
  382. auto time_bigint = Crypto::SignedBigInteger { time }.multiplied_by(s_one_million_bigint);
  383. offset_nanoseconds = get_named_time_zone_offset_nanoseconds(system_time_zone_identifier, time_bigint);
  384. }
  385. // 4. Let offsetMs be truncate(offsetNs / 10^6).
  386. auto offset_milliseconds = trunc(offset_nanoseconds / 1e6);
  387. // 5. Return t + ๐”ฝ(offsetMs).
  388. return time + offset_milliseconds;
  389. }
  390. // 21.4.1.26 UTC ( t ), https://tc39.es/ecma262/#sec-utc-t
  391. double utc_time(double time)
  392. {
  393. // 1. Let systemTimeZoneIdentifier be SystemTimeZoneIdentifier().
  394. auto system_time_zone_identifier = JS::system_time_zone_identifier();
  395. double offset_nanoseconds { 0 };
  396. // 2. If IsTimeZoneOffsetString(systemTimeZoneIdentifier) is true, then
  397. if (is_time_zone_offset_string(system_time_zone_identifier)) {
  398. // a. Let offsetNs be ParseTimeZoneOffsetString(systemTimeZoneIdentifier).
  399. offset_nanoseconds = parse_time_zone_offset_string(system_time_zone_identifier);
  400. }
  401. // 3. Else,
  402. else {
  403. // a. Let possibleInstants be GetNamedTimeZoneEpochNanoseconds(systemTimeZoneIdentifier, โ„(YearFromTime(t)), โ„(MonthFromTime(t)) + 1, โ„(DateFromTime(t)), โ„(HourFromTime(t)), โ„(MinFromTime(t)), โ„(SecFromTime(t)), โ„(msFromTime(t)), 0, 0).
  404. auto possible_instants = get_named_time_zone_epoch_nanoseconds(system_time_zone_identifier, year_from_time(time), month_from_time(time) + 1, date_from_time(time), hour_from_time(time), min_from_time(time), sec_from_time(time), ms_from_time(time), 0, 0);
  405. // b. NOTE: The following steps ensure that when t represents local time repeating multiple times at a negative time zone transition (e.g. when the daylight saving time ends or the time zone offset is decreased due to a time zone rule change) or skipped local time at a positive time zone transition (e.g. when the daylight saving time starts or the time zone offset is increased due to a time zone rule change), t is interpreted using the time zone offset before the transition.
  406. Crypto::SignedBigInteger disambiguated_instant;
  407. // c. If possibleInstants is not empty, then
  408. if (!possible_instants.is_empty()) {
  409. // i. Let disambiguatedInstant be possibleInstants[0].
  410. disambiguated_instant = move(possible_instants.first());
  411. }
  412. // d. Else,
  413. else {
  414. // i. NOTE: t represents a local time skipped at a positive time zone transition (e.g. due to daylight saving time starting or a time zone rule change increasing the UTC offset).
  415. // ii. Let possibleInstantsBefore be GetNamedTimeZoneEpochNanoseconds(systemTimeZoneIdentifier, โ„(YearFromTime(tBefore)), โ„(MonthFromTime(tBefore)) + 1, โ„(DateFromTime(tBefore)), โ„(HourFromTime(tBefore)), โ„(MinFromTime(tBefore)), โ„(SecFromTime(tBefore)), โ„(msFromTime(tBefore)), 0, 0), where tBefore is the largest integral Number < t for which possibleInstantsBefore is not empty (i.e., tBefore represents the last local time before the transition).
  416. // iii. Let disambiguatedInstant be the last element of possibleInstantsBefore.
  417. // FIXME: This branch currently cannot be reached with our implementation, because LibTimeZone does not handle skipped time points.
  418. // When GetNamedTimeZoneEpochNanoseconds is updated to use a LibTimeZone API which does handle them, implement these steps.
  419. VERIFY_NOT_REACHED();
  420. }
  421. // e. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, disambiguatedInstant).
  422. offset_nanoseconds = get_named_time_zone_offset_nanoseconds(system_time_zone_identifier, disambiguated_instant);
  423. }
  424. // 4. Let offsetMs be truncate(offsetNs / 10^6).
  425. auto offset_milliseconds = trunc(offset_nanoseconds / 1e6);
  426. // 5. Return t - ๐”ฝ(offsetMs).
  427. return time - offset_milliseconds;
  428. }
  429. // 21.4.1.27 MakeTime ( hour, min, sec, ms ), https://tc39.es/ecma262/#sec-maketime
  430. double make_time(double hour, double min, double sec, double ms)
  431. {
  432. // 1. If hour is not finite or min is not finite or sec is not finite or ms is not finite, return NaN.
  433. if (!isfinite(hour) || !isfinite(min) || !isfinite(sec) || !isfinite(ms))
  434. return NAN;
  435. // 2. Let h be ๐”ฝ(! ToIntegerOrInfinity(hour)).
  436. auto h = to_integer_or_infinity(hour);
  437. // 3. Let m be ๐”ฝ(! ToIntegerOrInfinity(min)).
  438. auto m = to_integer_or_infinity(min);
  439. // 4. Let s be ๐”ฝ(! ToIntegerOrInfinity(sec)).
  440. auto s = to_integer_or_infinity(sec);
  441. // 5. Let milli be ๐”ฝ(! ToIntegerOrInfinity(ms)).
  442. auto milli = to_integer_or_infinity(ms);
  443. // 6. Let t be ((h * msPerHour + m * msPerMinute) + s * msPerSecond) + milli, performing the arithmetic according to IEEE 754-2019 rules (that is, as if using the ECMAScript operators * and +).
  444. // NOTE: C++ arithmetic abides by IEEE 754 rules
  445. auto t = ((h * ms_per_hour + m * ms_per_minute) + s * ms_per_second) + milli;
  446. // 7. Return t.
  447. return t;
  448. }
  449. // 21.4.1.28 MakeDay ( year, month, date ), https://tc39.es/ecma262/#sec-makeday
  450. double make_day(double year, double month, double date)
  451. {
  452. // 1. If year is not finite or month is not finite or date is not finite, return NaN.
  453. if (!isfinite(year) || !isfinite(month) || !isfinite(date))
  454. return NAN;
  455. // 2. Let y be ๐”ฝ(! ToIntegerOrInfinity(year)).
  456. auto y = to_integer_or_infinity(year);
  457. // 3. Let m be ๐”ฝ(! ToIntegerOrInfinity(month)).
  458. auto m = to_integer_or_infinity(month);
  459. // 4. Let dt be ๐”ฝ(! ToIntegerOrInfinity(date)).
  460. auto dt = to_integer_or_infinity(date);
  461. // 5. Let ym be y + ๐”ฝ(floor(โ„(m) / 12)).
  462. auto ym = y + floor(m / 12);
  463. // 6. If ym is not finite, return NaN.
  464. if (!isfinite(ym))
  465. return NAN;
  466. // 7. Let mn be ๐”ฝ(โ„(m) modulo 12).
  467. auto mn = modulo(m, 12);
  468. // 8. Find a finite time value t such that YearFromTime(t) is ym and MonthFromTime(t) is mn and DateFromTime(t) is 1๐”ฝ; but if this is not possible (because some argument is out of range), return NaN.
  469. if (!AK::is_within_range<int>(ym) || !AK::is_within_range<int>(mn + 1))
  470. return NAN;
  471. auto t = days_since_epoch(static_cast<int>(ym), static_cast<int>(mn) + 1, 1) * ms_per_day;
  472. // 9. Return Day(t) + dt - 1๐”ฝ.
  473. return day(static_cast<double>(t)) + dt - 1;
  474. }
  475. // 21.4.1.29 MakeDate ( day, time ), https://tc39.es/ecma262/#sec-makedate
  476. double make_date(double day, double time)
  477. {
  478. // 1. If day is not finite or time is not finite, return NaN.
  479. if (!isfinite(day) || !isfinite(time))
  480. return NAN;
  481. // 2. Let tv be day ร— msPerDay + time.
  482. auto tv = day * ms_per_day + time;
  483. // 3. If tv is not finite, return NaN.
  484. if (!isfinite(tv))
  485. return NAN;
  486. // 4. Return tv.
  487. return tv;
  488. }
  489. // 21.4.1.31 TimeClip ( time ), https://tc39.es/ecma262/#sec-timeclip
  490. double time_clip(double time)
  491. {
  492. // 1. If time is not finite, return NaN.
  493. if (!isfinite(time))
  494. return NAN;
  495. // 2. If abs(โ„(time)) > 8.64 ร— 10^15, return NaN.
  496. if (fabs(time) > 8.64E15)
  497. return NAN;
  498. // 3. Return ๐”ฝ(! ToIntegerOrInfinity(time)).
  499. return to_integer_or_infinity(time);
  500. }
  501. // 21.4.1.33.1 IsTimeZoneOffsetString ( offsetString ), https://tc39.es/ecma262/#sec-istimezoneoffsetstring
  502. bool is_time_zone_offset_string(StringView offset_string)
  503. {
  504. // 1. Let parseResult be ParseText(StringToCodePoints(offsetString), UTCOffset).
  505. auto parse_result = Temporal::parse_iso8601(Temporal::Production::TimeZoneNumericUTCOffset, offset_string);
  506. // 2. If parseResult is a List of errors, return false.
  507. // 3. Return true.
  508. return parse_result.has_value();
  509. }
  510. // 21.4.1.33.2 ParseTimeZoneOffsetString ( offsetString ), https://tc39.es/ecma262/#sec-parsetimezoneoffsetstring
  511. double parse_time_zone_offset_string(StringView offset_string)
  512. {
  513. // 1. Let parseResult be ParseText(StringToCodePoints(offsetString), UTCOffset).
  514. auto parse_result = Temporal::parse_iso8601(Temporal::Production::TimeZoneNumericUTCOffset, offset_string);
  515. // 2. Assert: parseResult is not a List of errors.
  516. VERIFY(parse_result.has_value());
  517. // 3. Assert: parseResult contains a TemporalSign Parse Node.
  518. VERIFY(parse_result->time_zone_utc_offset_sign.has_value());
  519. // 4. Let parsedSign be the source text matched by the TemporalSign Parse Node contained within parseResult.
  520. auto parsed_sign = *parse_result->time_zone_utc_offset_sign;
  521. i8 sign { 0 };
  522. // 5. If parsedSign is the single code point U+002D (HYPHEN-MINUS) or U+2212 (MINUS SIGN), then
  523. if (parsed_sign.is_one_of("-"sv, "\xE2\x88\x92"sv)) {
  524. // a. Let sign be -1.
  525. sign = -1;
  526. }
  527. // 6. Else,
  528. else {
  529. // a. Let sign be 1.
  530. sign = 1;
  531. }
  532. // 7. NOTE: Applications of StringToNumber below do not lose precision, since each of the parsed values is guaranteed to be a sufficiently short string of decimal digits.
  533. // 8. Assert: parseResult contains an Hour Parse Node.
  534. VERIFY(parse_result->time_zone_utc_offset_hour.has_value());
  535. // 9. Let parsedHours be the source text matched by the Hour Parse Node contained within parseResult.
  536. auto parsed_hours = *parse_result->time_zone_utc_offset_hour;
  537. // 10. Let hours be โ„(StringToNumber(CodePointsToString(parsedHours))).
  538. auto hours = string_to_number(parsed_hours);
  539. double minutes { 0 };
  540. double seconds { 0 };
  541. double nanoseconds { 0 };
  542. // 11. If parseResult does not contain a MinuteSecond Parse Node, then
  543. if (!parse_result->time_zone_utc_offset_minute.has_value()) {
  544. // a. Let minutes be 0.
  545. minutes = 0;
  546. }
  547. // 12. Else,
  548. else {
  549. // a. Let parsedMinutes be the source text matched by the first MinuteSecond Parse Node contained within parseResult.
  550. auto parsed_minutes = *parse_result->time_zone_utc_offset_minute;
  551. // b. Let minutes be โ„(StringToNumber(CodePointsToString(parsedMinutes))).
  552. minutes = string_to_number(parsed_minutes);
  553. }
  554. // 13. If parseResult does not contain two MinuteSecond Parse Nodes, then
  555. if (!parse_result->time_zone_utc_offset_second.has_value()) {
  556. // a. Let seconds be 0.
  557. seconds = 0;
  558. }
  559. // 14. Else,
  560. else {
  561. // a. Let parsedSeconds be the source text matched by the second secondSecond Parse Node contained within parseResult.
  562. auto parsed_seconds = *parse_result->time_zone_utc_offset_second;
  563. // b. Let seconds be โ„(StringToNumber(CodePointsToString(parsedSeconds))).
  564. seconds = string_to_number(parsed_seconds);
  565. }
  566. // 15. If parseResult does not contain a TemporalDecimalFraction Parse Node, then
  567. if (!parse_result->time_zone_utc_offset_fraction.has_value()) {
  568. // a. Let nanoseconds be 0.
  569. nanoseconds = 0;
  570. }
  571. // 16. Else,
  572. else {
  573. // a. Let parsedFraction be the source text matched by the TemporalDecimalFraction Parse Node contained within parseResult.
  574. auto parsed_fraction = *parse_result->time_zone_utc_offset_fraction;
  575. // b. Let fraction be the string-concatenation of CodePointsToString(parsedFraction) and "000000000".
  576. auto fraction = ByteString::formatted("{}000000000", parsed_fraction);
  577. // c. Let nanosecondsString be the substring of fraction from 1 to 10.
  578. auto nanoseconds_string = fraction.substring_view(1, 9);
  579. // d. Let nanoseconds be โ„(StringToNumber(nanosecondsString)).
  580. nanoseconds = string_to_number(nanoseconds_string);
  581. }
  582. // 17. Return sign ร— (((hours ร— 60 + minutes) ร— 60 + seconds) ร— 10^9 + nanoseconds).
  583. // NOTE: Using scientific notation (1e9) ensures the result of this expression is a double,
  584. // which is important - otherwise it's all integers and the result overflows!
  585. return sign * (((hours * 60 + minutes) * 60 + seconds) * 1e9 + nanoseconds);
  586. }
  587. }