Date.cpp 29 KB

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