Date.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. /*
  2. * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2022-2024, Tim Flynn <trflynn89@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/CharacterTypes.h>
  8. #include <AK/GenericLexer.h>
  9. #include <AK/NumericLimits.h>
  10. #include <AK/ScopeGuard.h>
  11. #include <AK/StringBuilder.h>
  12. #include <AK/Time.h>
  13. #include <LibJS/Runtime/AbstractOperations.h>
  14. #include <LibJS/Runtime/Date.h>
  15. #include <LibJS/Runtime/GlobalObject.h>
  16. #include <LibJS/Runtime/Intl/AbstractOperations.h>
  17. #include <time.h>
  18. namespace JS {
  19. GC_DEFINE_ALLOCATOR(Date);
  20. static Crypto::SignedBigInteger const s_one_billion_bigint { 1'000'000'000 };
  21. static Crypto::SignedBigInteger const s_one_million_bigint { 1'000'000 };
  22. static Crypto::SignedBigInteger const s_one_thousand_bigint { 1'000 };
  23. Crypto::SignedBigInteger const ns_per_day_bigint { static_cast<i64>(ns_per_day) };
  24. GC::Ref<Date> Date::create(Realm& realm, double date_value)
  25. {
  26. return realm.create<Date>(date_value, realm.intrinsics().date_prototype());
  27. }
  28. Date::Date(double date_value, Object& prototype)
  29. : Object(ConstructWithPrototypeTag::Tag, prototype)
  30. , m_date_value(date_value)
  31. {
  32. }
  33. Date::~Date() = default;
  34. ErrorOr<String> Date::iso_date_string() const
  35. {
  36. int year = year_from_time(m_date_value);
  37. StringBuilder builder;
  38. if (year < 0)
  39. builder.appendff("-{:06}", -year);
  40. else if (year > 9999)
  41. builder.appendff("+{:06}", year);
  42. else
  43. builder.appendff("{:04}", year);
  44. builder.append('-');
  45. builder.appendff("{:02}", month_from_time(m_date_value) + 1);
  46. builder.append('-');
  47. builder.appendff("{:02}", date_from_time(m_date_value));
  48. builder.append('T');
  49. builder.appendff("{:02}", hour_from_time(m_date_value));
  50. builder.append(':');
  51. builder.appendff("{:02}", min_from_time(m_date_value));
  52. builder.append(':');
  53. builder.appendff("{:02}", sec_from_time(m_date_value));
  54. builder.append('.');
  55. builder.appendff("{:03}", ms_from_time(m_date_value));
  56. builder.append('Z');
  57. return builder.to_string();
  58. }
  59. // 21.4.1.3 Day ( t ), https://tc39.es/ecma262/#sec-day
  60. double day(double time_value)
  61. {
  62. // 1. Return 𝔽(floor(ℝ(t / msPerDay))).
  63. return floor(time_value / ms_per_day);
  64. }
  65. // 21.4.1.4 TimeWithinDay ( t ), https://tc39.es/ecma262/#sec-timewithinday
  66. double time_within_day(double time)
  67. {
  68. // 1. Return 𝔽(ℝ(t) modulo ℝ(msPerDay)).
  69. return modulo(time, ms_per_day);
  70. }
  71. // 21.4.1.5 DaysInYear ( y ), https://tc39.es/ecma262/#sec-daysinyear
  72. u16 days_in_year(i32 y)
  73. {
  74. // 1. Let ry be ℝ(y).
  75. auto ry = static_cast<double>(y);
  76. // 2. If (ry modulo 400) = 0, return 366𝔽.
  77. if (modulo(ry, 400.0) == 0)
  78. return 366;
  79. // 3. If (ry modulo 100) = 0, return 365𝔽.
  80. if (modulo(ry, 100.0) == 0)
  81. return 365;
  82. // 4. If (ry modulo 4) = 0, return 366𝔽.
  83. if (modulo(ry, 4.0) == 0)
  84. return 366;
  85. // 5. Return 365𝔽.
  86. return 365;
  87. }
  88. // 21.4.1.6 DayFromYear ( y ), https://tc39.es/ecma262/#sec-dayfromyear
  89. double day_from_year(i32 y)
  90. {
  91. // 1. Let ry be ℝ(y).
  92. auto ry = static_cast<double>(y);
  93. // 2. NOTE: In the following steps, each _numYearsN_ is the number of years divisible by N that occur between the
  94. // epoch and the start of year y. (The number is negative if y is before the epoch.)
  95. // 3. Let numYears1 be (ry - 1970).
  96. auto num_years_1 = ry - 1970;
  97. // 4. Let numYears4 be floor((ry - 1969) / 4).
  98. auto num_years_4 = floor((ry - 1969) / 4.0);
  99. // 5. Let numYears100 be floor((ry - 1901) / 100).
  100. auto num_years_100 = floor((ry - 1901) / 100.0);
  101. // 6. Let numYears400 be floor((ry - 1601) / 400).
  102. auto num_years_400 = floor((ry - 1601) / 400.0);
  103. // 7. Return 𝔽(365 × numYears1 + numYears4 - numYears100 + numYears400).
  104. return 365.0 * num_years_1 + num_years_4 - num_years_100 + num_years_400;
  105. }
  106. // 21.4.1.7 TimeFromYear ( y ), https://tc39.es/ecma262/#sec-timefromyear
  107. double time_from_year(i32 y)
  108. {
  109. // 1. Return msPerDay × DayFromYear(y).
  110. return ms_per_day * day_from_year(y);
  111. }
  112. // 21.4.1.8 YearFromTime ( t ), https://tc39.es/ecma262/#sec-yearfromtime
  113. i32 year_from_time(double t)
  114. {
  115. // 1. Return the largest integral Number y (closest to +∞) such that TimeFromYear(y) ≤ t.
  116. if (!Value(t).is_finite_number())
  117. return NumericLimits<i32>::max();
  118. // Approximation using average number of milliseconds per year. We might have to adjust this guess afterwards.
  119. auto year = static_cast<i32>(floor(t / (365.2425 * ms_per_day) + 1970));
  120. auto year_t = time_from_year(year);
  121. if (year_t > t)
  122. year--;
  123. else if (year_t + days_in_year(year) * ms_per_day <= t)
  124. year++;
  125. return year;
  126. }
  127. // 21.4.1.9 DayWithinYear ( t ), https://tc39.es/ecma262/#sec-daywithinyear
  128. u16 day_within_year(double t)
  129. {
  130. if (!Value(t).is_finite_number())
  131. return 0;
  132. // 1. Return Day(t) - DayFromYear(YearFromTime(t)).
  133. return static_cast<u16>(day(t) - day_from_year(year_from_time(t)));
  134. }
  135. // 21.4.1.10 InLeapYear ( t ), https://tc39.es/ecma262/#sec-inleapyear
  136. bool in_leap_year(double t)
  137. {
  138. // 1. If DaysInYear(YearFromTime(t)) is 366𝔽, return 1𝔽; else return +0𝔽.
  139. return days_in_year(year_from_time(t)) == 366;
  140. }
  141. // 21.4.1.11 MonthFromTime ( t ), https://tc39.es/ecma262/#sec-monthfromtime
  142. u8 month_from_time(double t)
  143. {
  144. // 1. Let inLeapYear be InLeapYear(t).
  145. auto in_leap_year = static_cast<unsigned>(JS::in_leap_year(t));
  146. // 2. Let dayWithinYear be DayWithinYear(t).
  147. auto day_within_year = JS::day_within_year(t);
  148. // 3. If dayWithinYear < 31𝔽, return +0𝔽.
  149. if (day_within_year < 31)
  150. return 0;
  151. // 4. If dayWithinYear < 59𝔽 + inLeapYear, return 1𝔽.
  152. if (day_within_year < (59 + in_leap_year))
  153. return 1;
  154. // 5. If dayWithinYear < 90𝔽 + inLeapYear, return 2𝔽.
  155. if (day_within_year < (90 + in_leap_year))
  156. return 2;
  157. // 6. If dayWithinYear < 120𝔽 + inLeapYear, return 3𝔽.
  158. if (day_within_year < (120 + in_leap_year))
  159. return 3;
  160. // 7. If dayWithinYear < 151𝔽 + inLeapYear, return 4𝔽.
  161. if (day_within_year < (151 + in_leap_year))
  162. return 4;
  163. // 8. If dayWithinYear < 181𝔽 + inLeapYear, return 5𝔽.
  164. if (day_within_year < (181 + in_leap_year))
  165. return 5;
  166. // 9. If dayWithinYear < 212𝔽 + inLeapYear, return 6𝔽.
  167. if (day_within_year < (212 + in_leap_year))
  168. return 6;
  169. // 10. If dayWithinYear < 243𝔽 + inLeapYear, return 7𝔽.
  170. if (day_within_year < (243 + in_leap_year))
  171. return 7;
  172. // 11. If dayWithinYear < 273𝔽 + inLeapYear, return 8𝔽.
  173. if (day_within_year < (273 + in_leap_year))
  174. return 8;
  175. // 12. If dayWithinYear < 304𝔽 + inLeapYear, return 9𝔽.
  176. if (day_within_year < (304 + in_leap_year))
  177. return 9;
  178. // 13. If dayWithinYear < 334𝔽 + inLeapYear, return 10𝔽.
  179. if (day_within_year < (334 + in_leap_year))
  180. return 10;
  181. // 14. Assert: dayWithinYear < 365𝔽 + inLeapYear.
  182. VERIFY(day_within_year < (365 + in_leap_year));
  183. // 15. Return 11𝔽.
  184. return 11;
  185. }
  186. // 21.4.1.12 DateFromTime ( t ), https://tc39.es/ecma262/#sec-datefromtime
  187. u8 date_from_time(double t)
  188. {
  189. // 1. Let inLeapYear be InLeapYear(t).
  190. auto in_leap_year = static_cast<unsigned>(JS::in_leap_year(t));
  191. // 2. Let dayWithinYear be DayWithinYear(t).
  192. auto day_within_year = JS::day_within_year(t);
  193. // 3. Let month be MonthFromTime(t).
  194. auto month = month_from_time(t);
  195. // 4. If month is +0𝔽, return dayWithinYear + 1𝔽.
  196. if (month == 0)
  197. return day_within_year + 1;
  198. // 5. If month is 1𝔽, return dayWithinYear - 30𝔽.
  199. if (month == 1)
  200. return day_within_year - 30;
  201. // 6. If month is 2𝔽, return dayWithinYear - 58𝔽 - inLeapYear.
  202. if (month == 2)
  203. return day_within_year - 58 - in_leap_year;
  204. // 7. If month is 3𝔽, return dayWithinYear - 89𝔽 - inLeapYear.
  205. if (month == 3)
  206. return day_within_year - 89 - in_leap_year;
  207. // 8. If month is 4𝔽, return dayWithinYear - 119𝔽 - inLeapYear.
  208. if (month == 4)
  209. return day_within_year - 119 - in_leap_year;
  210. // 9. If month is 5𝔽, return dayWithinYear - 150𝔽 - inLeapYear.
  211. if (month == 5)
  212. return day_within_year - 150 - in_leap_year;
  213. // 10. If month is 6𝔽, return dayWithinYear - 180𝔽 - inLeapYear.
  214. if (month == 6)
  215. return day_within_year - 180 - in_leap_year;
  216. // 11. If month is 7𝔽, return dayWithinYear - 211𝔽 - inLeapYear.
  217. if (month == 7)
  218. return day_within_year - 211 - in_leap_year;
  219. // 12. If month is 8𝔽, return dayWithinYear - 242𝔽 - inLeapYear.
  220. if (month == 8)
  221. return day_within_year - 242 - in_leap_year;
  222. // 13. If month is 9𝔽, return dayWithinYear - 272𝔽 - inLeapYear.
  223. if (month == 9)
  224. return day_within_year - 272 - in_leap_year;
  225. // 14. If month is 10𝔽, return dayWithinYear - 303𝔽 - inLeapYear.
  226. if (month == 10)
  227. return day_within_year - 303 - in_leap_year;
  228. // 15. Assert: month is 11𝔽.
  229. VERIFY(month == 11);
  230. // 16. Return dayWithinYear - 333𝔽 - inLeapYear.
  231. return day_within_year - 333 - in_leap_year;
  232. }
  233. // 21.4.1.13 WeekDay ( t ), https://tc39.es/ecma262/#sec-weekday
  234. u8 week_day(double t)
  235. {
  236. if (!Value(t).is_finite_number())
  237. return 0;
  238. // 1. Return 𝔽(ℝ(Day(t) + 4𝔽) modulo 7).
  239. return static_cast<u8>(modulo(day(t) + 4, 7));
  240. }
  241. // 21.4.1.14 HourFromTime ( t ), https://tc39.es/ecma262/#sec-hourfromtime
  242. u8 hour_from_time(double t)
  243. {
  244. if (!Value(t).is_finite_number())
  245. return 0;
  246. // 1. Return 𝔽(floor(ℝ(t / msPerHour)) modulo HoursPerDay).
  247. return static_cast<u8>(modulo(floor(t / ms_per_hour), hours_per_day));
  248. }
  249. // 21.4.1.15 MinFromTime ( t ), https://tc39.es/ecma262/#sec-minfromtime
  250. u8 min_from_time(double t)
  251. {
  252. if (!Value(t).is_finite_number())
  253. return 0;
  254. // 1. Return 𝔽(floor(ℝ(t / msPerMinute)) modulo MinutesPerHour).
  255. return static_cast<u8>(modulo(floor(t / ms_per_minute), minutes_per_hour));
  256. }
  257. // 21.4.1.16 SecFromTime ( t ), https://tc39.es/ecma262/#sec-secfromtime
  258. u8 sec_from_time(double t)
  259. {
  260. if (!Value(t).is_finite_number())
  261. return 0;
  262. // 1. Return 𝔽(floor(ℝ(t / msPerSecond)) modulo SecondsPerMinute).
  263. return static_cast<u8>(modulo(floor(t / ms_per_second), seconds_per_minute));
  264. }
  265. // 21.4.1.17 msFromTime ( t ), https://tc39.es/ecma262/#sec-msfromtime
  266. u16 ms_from_time(double t)
  267. {
  268. if (!Value(t).is_finite_number())
  269. return 0;
  270. // 1. Return 𝔽(ℝ(t) modulo ℝ(msPerSecond)).
  271. return static_cast<u16>(modulo(t, ms_per_second));
  272. }
  273. // 21.4.1.18 GetUTCEpochNanoseconds ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/ecma262/#sec-getutcepochnanoseconds
  274. Crypto::SignedBigInteger get_utc_epoch_nanoseconds(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond)
  275. {
  276. // 1. Let date be MakeDay(𝔽(year), 𝔽(month - 1), 𝔽(day)).
  277. auto date = make_day(year, month - 1, day);
  278. // 2. Let time be MakeTime(𝔽(hour), 𝔽(minute), 𝔽(second), 𝔽(millisecond)).
  279. auto time = make_time(hour, minute, second, millisecond);
  280. // 3. Let ms be MakeDate(date, time).
  281. auto ms = make_date(date, time);
  282. // 4. Assert: ms is an integral Number.
  283. VERIFY(ms == trunc(ms));
  284. // 5. Return ℤ(ℝ(ms) × 10^6 + microsecond × 10^3 + nanosecond).
  285. auto result = Crypto::SignedBigInteger { ms }.multiplied_by(s_one_million_bigint);
  286. result = result.plus(Crypto::SignedBigInteger { static_cast<i32>(microsecond) }.multiplied_by(s_one_thousand_bigint));
  287. result = result.plus(Crypto::SignedBigInteger { static_cast<i32>(nanosecond) });
  288. return result;
  289. }
  290. static i64 clip_bigint_to_sane_time(Crypto::SignedBigInteger const& value)
  291. {
  292. static Crypto::SignedBigInteger const min_bigint { NumericLimits<i64>::min() };
  293. static Crypto::SignedBigInteger const max_bigint { NumericLimits<i64>::max() };
  294. // The provided epoch (nano)seconds value is potentially out of range for AK::Duration and subsequently
  295. // get_time_zone_offset(). We can safely assume that the TZDB has no useful information that far
  296. // into the past and future anyway, so clamp it to the i64 range.
  297. if (value < min_bigint)
  298. return NumericLimits<i64>::min();
  299. if (value > max_bigint)
  300. return NumericLimits<i64>::max();
  301. // FIXME: Can we do this without string conversion?
  302. return value.to_base_deprecated(10).to_number<i64>().value();
  303. }
  304. static i64 clip_double_to_sane_time(double value)
  305. {
  306. static constexpr auto min_double = static_cast<double>(NumericLimits<i64>::min());
  307. static constexpr auto max_double = static_cast<double>(NumericLimits<i64>::max());
  308. // The provided epoch millseconds value is potentially out of range for AK::Duration and subsequently
  309. // get_time_zone_offset(). We can safely assume that the TZDB has no useful information that far
  310. // into the past and future anyway, so clamp it to the i64 range.
  311. if (value < min_double)
  312. return NumericLimits<i64>::min();
  313. if (value > max_double)
  314. return NumericLimits<i64>::max();
  315. return static_cast<i64>(value);
  316. }
  317. // 21.4.1.20 GetNamedTimeZoneEpochNanoseconds ( timeZoneIdentifier, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/ecma262/#sec-getnamedtimezoneepochnanoseconds
  318. 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)
  319. {
  320. auto local_nanoseconds = get_utc_epoch_nanoseconds(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond);
  321. auto local_time = UnixDateTime::from_nanoseconds_since_epoch(clip_bigint_to_sane_time(local_nanoseconds));
  322. // FIXME: LibUnicode does not behave exactly as the spec expects. It does not consider repeated or skipped time points.
  323. auto offset = Unicode::time_zone_offset(time_zone_identifier, local_time);
  324. // Can only fail if the time zone identifier is invalid, which cannot be the case here.
  325. VERIFY(offset.has_value());
  326. return { local_nanoseconds.minus(Crypto::SignedBigInteger { offset->offset.to_nanoseconds() }) };
  327. }
  328. // 21.4.1.21 GetNamedTimeZoneOffsetNanoseconds ( timeZoneIdentifier, epochNanoseconds ), https://tc39.es/ecma262/#sec-getnamedtimezoneoffsetnanoseconds
  329. Unicode::TimeZoneOffset get_named_time_zone_offset_nanoseconds(StringView time_zone_identifier, Crypto::SignedBigInteger const& epoch_nanoseconds)
  330. {
  331. // Since UnixDateTime::from_seconds_since_epoch() and UnixDateTime::from_nanoseconds_since_epoch() both take an i64, converting to
  332. // seconds first gives us a greater range. The TZDB doesn't have sub-second offsets.
  333. auto seconds = epoch_nanoseconds.divided_by(s_one_billion_bigint).quotient;
  334. auto time = UnixDateTime::from_seconds_since_epoch(clip_bigint_to_sane_time(seconds));
  335. auto offset = Unicode::time_zone_offset(time_zone_identifier, time);
  336. VERIFY(offset.has_value());
  337. return offset.release_value();
  338. }
  339. // 21.4.1.21 GetNamedTimeZoneOffsetNanoseconds ( timeZoneIdentifier, epochNanoseconds ), https://tc39.es/ecma262/#sec-getnamedtimezoneoffsetnanoseconds
  340. // OPTIMIZATION: This overload is provided to allow callers to avoid BigInt construction if they do not need infinitely precise nanosecond resolution.
  341. Unicode::TimeZoneOffset get_named_time_zone_offset_milliseconds(StringView time_zone_identifier, double epoch_milliseconds)
  342. {
  343. auto seconds = epoch_milliseconds / 1000.0;
  344. auto time = UnixDateTime::from_seconds_since_epoch(clip_double_to_sane_time(seconds));
  345. auto offset = Unicode::time_zone_offset(time_zone_identifier, time);
  346. VERIFY(offset.has_value());
  347. return offset.release_value();
  348. }
  349. static Optional<String> cached_system_time_zone_identifier;
  350. // 21.4.1.24 SystemTimeZoneIdentifier ( ), https://tc39.es/ecma262/#sec-systemtimezoneidentifier
  351. String system_time_zone_identifier()
  352. {
  353. // OPTIMIZATION: We cache the system time zone to avoid the expensive lookups below.
  354. if (cached_system_time_zone_identifier.has_value())
  355. return *cached_system_time_zone_identifier;
  356. // 1. If the implementation only supports the UTC time zone, return "UTC".
  357. // 2. Let systemTimeZoneString be the String representing the host environment's current time zone, either a primary
  358. // time zone identifier or an offset time zone identifier.
  359. auto system_time_zone_string = Unicode::current_time_zone();
  360. if (!is_time_zone_offset_string(system_time_zone_string)) {
  361. auto time_zone_identifier = Intl::get_available_named_time_zone_identifier(system_time_zone_string);
  362. if (!time_zone_identifier.has_value())
  363. return "UTC"_string;
  364. system_time_zone_string = time_zone_identifier->primary_identifier;
  365. }
  366. // 3. Return systemTimeZoneString.
  367. cached_system_time_zone_identifier = move(system_time_zone_string);
  368. return *cached_system_time_zone_identifier;
  369. }
  370. void clear_system_time_zone_cache()
  371. {
  372. cached_system_time_zone_identifier.clear();
  373. }
  374. // 21.4.1.25 LocalTime ( t ), https://tc39.es/ecma262/#sec-localtime
  375. double local_time(double time)
  376. {
  377. // 1. Let systemTimeZoneIdentifier be SystemTimeZoneIdentifier().
  378. auto system_time_zone_identifier = JS::system_time_zone_identifier();
  379. double offset_nanoseconds { 0 };
  380. // 2. If IsTimeZoneOffsetString(systemTimeZoneIdentifier) is true, then
  381. if (is_time_zone_offset_string(system_time_zone_identifier)) {
  382. // a. Let offsetNs be ParseTimeZoneOffsetString(systemTimeZoneIdentifier).
  383. offset_nanoseconds = parse_time_zone_offset_string(system_time_zone_identifier);
  384. }
  385. // 3. Else,
  386. else {
  387. // a. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, ℤ(ℝ(t) × 10^6)).
  388. auto offset = get_named_time_zone_offset_milliseconds(system_time_zone_identifier, time);
  389. offset_nanoseconds = static_cast<double>(offset.offset.to_nanoseconds());
  390. }
  391. // 4. Let offsetMs be truncate(offsetNs / 10^6).
  392. auto offset_milliseconds = trunc(offset_nanoseconds / 1e6);
  393. // 5. Return t + 𝔽(offsetMs).
  394. return time + offset_milliseconds;
  395. }
  396. // 21.4.1.26 UTC ( t ), https://tc39.es/ecma262/#sec-utc-t
  397. double utc_time(double time)
  398. {
  399. // 1. Let systemTimeZoneIdentifier be SystemTimeZoneIdentifier().
  400. auto system_time_zone_identifier = JS::system_time_zone_identifier();
  401. double offset_nanoseconds { 0 };
  402. // 2. If IsTimeZoneOffsetString(systemTimeZoneIdentifier) is true, then
  403. if (is_time_zone_offset_string(system_time_zone_identifier)) {
  404. // a. Let offsetNs be ParseTimeZoneOffsetString(systemTimeZoneIdentifier).
  405. offset_nanoseconds = parse_time_zone_offset_string(system_time_zone_identifier);
  406. }
  407. // 3. Else,
  408. else {
  409. // a. Let possibleInstants be GetNamedTimeZoneEpochNanoseconds(systemTimeZoneIdentifier, ℝ(YearFromTime(t)), ℝ(MonthFromTime(t)) + 1, ℝ(DateFromTime(t)), ℝ(HourFromTime(t)), ℝ(MinFromTime(t)), ℝ(SecFromTime(t)), ℝ(msFromTime(t)), 0, 0).
  410. 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);
  411. // 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.
  412. Crypto::SignedBigInteger disambiguated_instant;
  413. // c. If possibleInstants is not empty, then
  414. if (!possible_instants.is_empty()) {
  415. // i. Let disambiguatedInstant be possibleInstants[0].
  416. disambiguated_instant = move(possible_instants.first());
  417. }
  418. // d. Else,
  419. else {
  420. // 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).
  421. // 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).
  422. // iii. Let disambiguatedInstant be the last element of possibleInstantsBefore.
  423. // FIXME: This branch currently cannot be reached with our implementation, because LibUnicode does not handle skipped time points.
  424. // When GetNamedTimeZoneEpochNanoseconds is updated to use a LibUnicode API which does handle them, implement these steps.
  425. VERIFY_NOT_REACHED();
  426. }
  427. // e. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, disambiguatedInstant).
  428. auto offset = get_named_time_zone_offset_nanoseconds(system_time_zone_identifier, disambiguated_instant);
  429. offset_nanoseconds = static_cast<double>(offset.offset.to_nanoseconds());
  430. }
  431. // 4. Let offsetMs be truncate(offsetNs / 10^6).
  432. auto offset_milliseconds = trunc(offset_nanoseconds / 1e6);
  433. // 5. Return t - 𝔽(offsetMs).
  434. return time - offset_milliseconds;
  435. }
  436. // 21.4.1.27 MakeTime ( hour, min, sec, ms ), https://tc39.es/ecma262/#sec-maketime
  437. double make_time(double hour, double min, double sec, double ms)
  438. {
  439. // 1. If hour is not finite or min is not finite or sec is not finite or ms is not finite, return NaN.
  440. if (!isfinite(hour) || !isfinite(min) || !isfinite(sec) || !isfinite(ms))
  441. return NAN;
  442. // 2. Let h be 𝔽(! ToIntegerOrInfinity(hour)).
  443. auto h = to_integer_or_infinity(hour);
  444. // 3. Let m be 𝔽(! ToIntegerOrInfinity(min)).
  445. auto m = to_integer_or_infinity(min);
  446. // 4. Let s be 𝔽(! ToIntegerOrInfinity(sec)).
  447. auto s = to_integer_or_infinity(sec);
  448. // 5. Let milli be 𝔽(! ToIntegerOrInfinity(ms)).
  449. auto milli = to_integer_or_infinity(ms);
  450. // 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 +).
  451. // NOTE: C++ arithmetic abides by IEEE 754 rules
  452. auto t = ((h * ms_per_hour + m * ms_per_minute) + s * ms_per_second) + milli;
  453. // 7. Return t.
  454. return t;
  455. }
  456. // 21.4.1.28 MakeDay ( year, month, date ), https://tc39.es/ecma262/#sec-makeday
  457. double make_day(double year, double month, double date)
  458. {
  459. // 1. If year is not finite or month is not finite or date is not finite, return NaN.
  460. if (!isfinite(year) || !isfinite(month) || !isfinite(date))
  461. return NAN;
  462. // 2. Let y be 𝔽(! ToIntegerOrInfinity(year)).
  463. auto y = to_integer_or_infinity(year);
  464. // 3. Let m be 𝔽(! ToIntegerOrInfinity(month)).
  465. auto m = to_integer_or_infinity(month);
  466. // 4. Let dt be 𝔽(! ToIntegerOrInfinity(date)).
  467. auto dt = to_integer_or_infinity(date);
  468. // 5. Let ym be y + 𝔽(floor(ℝ(m) / 12)).
  469. auto ym = y + floor(m / 12);
  470. // 6. If ym is not finite, return NaN.
  471. if (!isfinite(ym))
  472. return NAN;
  473. // 7. Let mn be 𝔽(ℝ(m) modulo 12).
  474. auto mn = modulo(m, 12);
  475. // 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.
  476. if (!AK::is_within_range<int>(ym) || !AK::is_within_range<int>(mn + 1))
  477. return NAN;
  478. auto t = days_since_epoch(static_cast<int>(ym), static_cast<int>(mn) + 1, 1) * ms_per_day;
  479. // 9. Return Day(t) + dt - 1𝔽.
  480. return day(static_cast<double>(t)) + dt - 1;
  481. }
  482. // 21.4.1.29 MakeDate ( day, time ), https://tc39.es/ecma262/#sec-makedate
  483. double make_date(double day, double time)
  484. {
  485. // 1. If day is not finite or time is not finite, return NaN.
  486. if (!isfinite(day) || !isfinite(time))
  487. return NAN;
  488. // 2. Let tv be day × msPerDay + time.
  489. auto tv = day * ms_per_day + time;
  490. // 3. If tv is not finite, return NaN.
  491. if (!isfinite(tv))
  492. return NAN;
  493. // 4. Return tv.
  494. return tv;
  495. }
  496. // 21.4.1.31 TimeClip ( time ), https://tc39.es/ecma262/#sec-timeclip
  497. double time_clip(double time)
  498. {
  499. // 1. If time is not finite, return NaN.
  500. if (!isfinite(time))
  501. return NAN;
  502. // 2. If abs(ℝ(time)) > 8.64 × 10^15, return NaN.
  503. if (fabs(time) > 8.64E15)
  504. return NAN;
  505. // 3. Return 𝔽(! ToIntegerOrInfinity(time)).
  506. return to_integer_or_infinity(time);
  507. }
  508. // 21.4.1.33 Time Zone Offset String Format, https://tc39.es/ecma262/#sec-time-zone-offset-strings
  509. Optional<UTCOffset> parse_utc_offset(StringView offset_string)
  510. {
  511. GenericLexer lexer { offset_string };
  512. UTCOffset parse_result;
  513. // https://tc39.es/ecma262/#prod-ASCIISign
  514. auto parse_ascii_sign = [&]() {
  515. // ASCIISign ::: one of
  516. // + -
  517. if (lexer.next_is(is_any_of("+-"sv))) {
  518. parse_result.sign = lexer.consume();
  519. return true;
  520. }
  521. return false;
  522. };
  523. auto parse_two_digits = [&](size_t max_value) -> Optional<u8> {
  524. if (auto digits = lexer.peek_string(2); digits.has_value()) {
  525. auto number = digits->to_number<u8>(TrimWhitespace::No);
  526. if (number.has_value() && *number <= max_value) {
  527. lexer.ignore(2);
  528. return *number;
  529. }
  530. }
  531. return {};
  532. };
  533. // https://tc39.es/ecma262/#prod-Hour
  534. auto parse_hour = [&]() {
  535. // Hour :::
  536. // 0 DecimalDigit
  537. // 1 DecimalDigit
  538. // 20
  539. // 21
  540. // 22
  541. // 23
  542. parse_result.hour = parse_two_digits(23);
  543. return parse_result.hour.has_value();
  544. };
  545. // https://tc39.es/ecma262/#prod-TimeSeparator
  546. auto parse_time_separator = [&](auto extended) {
  547. // TimeSeparator[Extended] :::
  548. // [+Extended] :
  549. // [~Extended] [empty]
  550. if (extended)
  551. return lexer.consume_specific(':');
  552. return true;
  553. };
  554. // https://tc39.es/ecma262/#prod-MinuteSecond
  555. auto parse_minute_second = [&](auto& result) {
  556. // MinuteSecond :::
  557. // 0 DecimalDigit
  558. // 1 DecimalDigit
  559. // 2 DecimalDigit
  560. // 3 DecimalDigit
  561. // 4 DecimalDigit
  562. // 5 DecimalDigit
  563. result = parse_two_digits(59);
  564. return result.has_value();
  565. };
  566. // https://tc39.es/ecma262/#prod-TemporalDecimalSeparator
  567. auto parse_temporal_decimal_separator = [&]() {
  568. // TemporalDecimalSeparator ::: one of
  569. // . ,
  570. return lexer.consume_specific('.') || lexer.consume_specific(',');
  571. };
  572. // https://tc39.es/ecma262/#prod-TemporalDecimalFraction
  573. auto parse_temporal_decimal_fraction = [&]() {
  574. // TemporalDecimalFraction :::
  575. // TemporalDecimalSeparator DecimalDigit
  576. // TemporalDecimalSeparator DecimalDigit DecimalDigit
  577. // TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit
  578. // TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit
  579. // TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit
  580. // TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit
  581. // TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit
  582. // TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit
  583. // TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit
  584. auto position = lexer.tell();
  585. if (!parse_temporal_decimal_separator())
  586. return false;
  587. for (size_t i = 0; i < 9; ++i) {
  588. if (!lexer.next_is(is_ascii_digit))
  589. break;
  590. lexer.ignore();
  591. }
  592. if (auto fraction = lexer.input().substring_view(position, lexer.tell() - position); fraction.length() > 1) {
  593. parse_result.fraction = fraction;
  594. return true;
  595. }
  596. return false;
  597. };
  598. // https://tc39.es/ecma262/#prod-HourSubcomponents
  599. auto parse_hour_subcomponents = [&](auto extended) {
  600. // HourSubcomponents[Extended] :::
  601. // TimeSeparator[?Extended] MinuteSecond
  602. // TimeSeparator[?Extended] MinuteSecond TimeSeparator[?Extended] MinuteSecond TemporalDecimalFraction[opt]
  603. ArmedScopeGuard guard { [&, position = lexer.tell()]() { lexer.retreat(lexer.tell() - position); } };
  604. if (!parse_time_separator(extended))
  605. return false;
  606. if (!parse_minute_second(parse_result.minute))
  607. return false;
  608. if (lexer.is_eof()) {
  609. guard.disarm();
  610. return true;
  611. }
  612. if (!parse_time_separator(extended))
  613. return false;
  614. if (!parse_minute_second(parse_result.second))
  615. return false;
  616. if (lexer.is_eof()) {
  617. guard.disarm();
  618. return true;
  619. }
  620. if (!parse_temporal_decimal_fraction())
  621. return false;
  622. guard.disarm();
  623. return true;
  624. };
  625. // https://tc39.es/ecma262/#prod-UTCOffset
  626. // UTCOffset :::
  627. // ASCIISign Hour
  628. // ASCIISign Hour HourSubcomponents[+Extended]
  629. // ASCIISign Hour HourSubcomponents[~Extended]
  630. if (!parse_ascii_sign())
  631. return {};
  632. if (!parse_hour())
  633. return {};
  634. if (lexer.is_eof())
  635. return parse_result;
  636. if (!parse_hour_subcomponents(true) && !parse_hour_subcomponents(false))
  637. return {};
  638. if (lexer.is_eof())
  639. return parse_result;
  640. return {};
  641. }
  642. // 21.4.1.33.1 IsTimeZoneOffsetString ( offsetString ), https://tc39.es/ecma262/#sec-istimezoneoffsetstring
  643. bool is_time_zone_offset_string(StringView offset_string)
  644. {
  645. // 1. Let parseResult be ParseText(StringToCodePoints(offsetString), UTCOffset).
  646. auto parse_result = parse_utc_offset(offset_string);
  647. // 2. If parseResult is a List of errors, return false.
  648. // 3. Return true.
  649. return parse_result.has_value();
  650. }
  651. // 21.4.1.33.2 ParseTimeZoneOffsetString ( offsetString ), https://tc39.es/ecma262/#sec-parsetimezoneoffsetstring
  652. double parse_time_zone_offset_string(StringView offset_string)
  653. {
  654. // 1. Let parseResult be ParseText(offsetString, UTCOffset).
  655. auto parse_result = parse_utc_offset(offset_string);
  656. // 2. Assert: parseResult is not a List of errors.
  657. VERIFY(parse_result.has_value());
  658. // 3. Assert: parseResult contains a ASCIISign Parse Node.
  659. VERIFY(parse_result->sign.has_value());
  660. // 4. Let parsedSign be the source text matched by the ASCIISign Parse Node contained within parseResult.
  661. auto parsed_sign = *parse_result->sign;
  662. i8 sign { 0 };
  663. // 5. If parsedSign is the single code point U+002D (HYPHEN-MINUS), then
  664. if (parsed_sign == '-') {
  665. // a. Let sign be -1.
  666. sign = -1;
  667. }
  668. // 6. Else,
  669. else {
  670. // a. Let sign be 1.
  671. sign = 1;
  672. }
  673. // 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.
  674. // 8. Assert: parseResult contains an Hour Parse Node.
  675. VERIFY(parse_result->hour.has_value());
  676. // 9. Let parsedHours be the source text matched by the Hour Parse Node contained within parseResult.
  677. // 10. Let hours be ℝ(StringToNumber(CodePointsToString(parsedHours))).
  678. auto hours = *parse_result->hour;
  679. // 11. If parseResult does not contain a MinuteSecond Parse Node, then
  680. // a. Let minutes be 0.
  681. // 12. Else,
  682. // a. Let parsedMinutes be the source text matched by the first MinuteSecond Parse Node contained within parseResult.
  683. // b. Let minutes be ℝ(StringToNumber(CodePointsToString(parsedMinutes))).
  684. double minutes = parse_result->minute.value_or(0);
  685. // 13. If parseResult does not contain two MinuteSecond Parse Nodes, then
  686. // a. Let seconds be 0.
  687. // 14. Else,
  688. // a. Let parsedSeconds be the source text matched by the second secondSecond Parse Node contained within parseResult.
  689. // b. Let seconds be ℝ(StringToNumber(CodePointsToString(parsedSeconds))).
  690. double seconds = parse_result->second.value_or(0);
  691. double nanoseconds = 0;
  692. // 15. If parseResult does not contain a TemporalDecimalFraction Parse Node, then
  693. if (!parse_result->fraction.has_value()) {
  694. // a. Let nanoseconds be 0.
  695. nanoseconds = 0;
  696. }
  697. // 16. Else,
  698. else {
  699. // a. Let parsedFraction be the source text matched by the TemporalDecimalFraction Parse Node contained within parseResult.
  700. auto parsed_fraction = *parse_result->fraction;
  701. // b. Let fraction be the string-concatenation of CodePointsToString(parsedFraction) and "000000000".
  702. auto fraction = ByteString::formatted("{}000000000", parsed_fraction);
  703. // c. Let nanosecondsString be the substring of fraction from 1 to 10.
  704. auto nanoseconds_string = fraction.substring_view(1, 9);
  705. // d. Let nanoseconds be ℝ(StringToNumber(nanosecondsString)).
  706. nanoseconds = string_to_number(nanoseconds_string);
  707. }
  708. // 17. Return sign × (((hours × 60 + minutes) × 60 + seconds) × 10^9 + nanoseconds).
  709. // NOTE: Using scientific notation (1e9) ensures the result of this expression is a double,
  710. // which is important - otherwise it's all integers and the result overflows!
  711. return sign * (((hours * 60 + minutes) * 60 + seconds) * 1e9 + nanoseconds);
  712. }
  713. }