Date.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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/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/Intl/AbstractOperations.h>
  14. #include <LibJS/Runtime/Temporal/ISO8601.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.create<Date>(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. static i64 clip_double_to_sane_time(double value)
  303. {
  304. static constexpr auto min_double = static_cast<double>(NumericLimits<i64>::min());
  305. static constexpr auto max_double = static_cast<double>(NumericLimits<i64>::max());
  306. // The provided epoch millseconds value is potentially out of range for AK::Duration and subsequently
  307. // get_time_zone_offset(). We can safely assume that the TZDB has no useful information that far
  308. // into the past and future anyway, so clamp it to the i64 range.
  309. if (value < min_double)
  310. return NumericLimits<i64>::min();
  311. if (value > max_double)
  312. return NumericLimits<i64>::max();
  313. return static_cast<i64>(value);
  314. }
  315. // 21.4.1.20 GetNamedTimeZoneEpochNanoseconds ( timeZoneIdentifier, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/ecma262/#sec-getnamedtimezoneepochnanoseconds
  316. 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)
  317. {
  318. auto local_nanoseconds = get_utc_epoch_nanoseconds(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond);
  319. auto local_time = UnixDateTime::from_nanoseconds_since_epoch(clip_bigint_to_sane_time(local_nanoseconds));
  320. // FIXME: LibUnicode does not behave exactly as the spec expects. It does not consider repeated or skipped time points.
  321. auto offset = Unicode::time_zone_offset(time_zone_identifier, local_time);
  322. // Can only fail if the time zone identifier is invalid, which cannot be the case here.
  323. VERIFY(offset.has_value());
  324. return { local_nanoseconds.minus(Crypto::SignedBigInteger { offset->offset.to_nanoseconds() }) };
  325. }
  326. // 21.4.1.21 GetNamedTimeZoneOffsetNanoseconds ( timeZoneIdentifier, epochNanoseconds ), https://tc39.es/ecma262/#sec-getnamedtimezoneoffsetnanoseconds
  327. Unicode::TimeZoneOffset get_named_time_zone_offset_nanoseconds(StringView time_zone_identifier, Crypto::SignedBigInteger const& epoch_nanoseconds)
  328. {
  329. // Since UnixDateTime::from_seconds_since_epoch() and UnixDateTime::from_nanoseconds_since_epoch() both take an i64, converting to
  330. // seconds first gives us a greater range. The TZDB doesn't have sub-second offsets.
  331. auto seconds = epoch_nanoseconds.divided_by(s_one_billion_bigint).quotient;
  332. auto time = UnixDateTime::from_seconds_since_epoch(clip_bigint_to_sane_time(seconds));
  333. auto offset = Unicode::time_zone_offset(time_zone_identifier, time);
  334. VERIFY(offset.has_value());
  335. return offset.release_value();
  336. }
  337. // 21.4.1.21 GetNamedTimeZoneOffsetNanoseconds ( timeZoneIdentifier, epochNanoseconds ), https://tc39.es/ecma262/#sec-getnamedtimezoneoffsetnanoseconds
  338. // OPTIMIZATION: This overload is provided to allow callers to avoid BigInt construction if they do not need infinitely precise nanosecond resolution.
  339. Unicode::TimeZoneOffset get_named_time_zone_offset_milliseconds(StringView time_zone_identifier, double epoch_milliseconds)
  340. {
  341. auto seconds = epoch_milliseconds / 1000.0;
  342. auto time = UnixDateTime::from_seconds_since_epoch(clip_double_to_sane_time(seconds));
  343. auto offset = Unicode::time_zone_offset(time_zone_identifier, time);
  344. VERIFY(offset.has_value());
  345. return offset.release_value();
  346. }
  347. static Optional<String> cached_system_time_zone_identifier;
  348. // 21.4.1.24 SystemTimeZoneIdentifier ( ), https://tc39.es/ecma262/#sec-systemtimezoneidentifier
  349. String system_time_zone_identifier()
  350. {
  351. // OPTIMIZATION: We cache the system time zone to avoid the expensive lookups below.
  352. if (cached_system_time_zone_identifier.has_value())
  353. return *cached_system_time_zone_identifier;
  354. // 1. If the implementation only supports the UTC time zone, return "UTC".
  355. // 2. Let systemTimeZoneString be the String representing the host environment's current time zone, either a primary
  356. // time zone identifier or an offset time zone identifier.
  357. auto system_time_zone_string = Unicode::current_time_zone();
  358. if (!is_time_zone_offset_string(system_time_zone_string)) {
  359. auto time_zone_identifier = Intl::get_available_named_time_zone_identifier(system_time_zone_string);
  360. if (!time_zone_identifier.has_value())
  361. return "UTC"_string;
  362. system_time_zone_string = time_zone_identifier->primary_identifier;
  363. }
  364. // 3. Return systemTimeZoneString.
  365. cached_system_time_zone_identifier = move(system_time_zone_string);
  366. return *cached_system_time_zone_identifier;
  367. }
  368. void clear_system_time_zone_cache()
  369. {
  370. cached_system_time_zone_identifier.clear();
  371. }
  372. // 21.4.1.25 LocalTime ( t ), https://tc39.es/ecma262/#sec-localtime
  373. double local_time(double time)
  374. {
  375. // 1. Let systemTimeZoneIdentifier be SystemTimeZoneIdentifier().
  376. auto system_time_zone_identifier = JS::system_time_zone_identifier();
  377. double offset_nanoseconds { 0 };
  378. // 2. If IsTimeZoneOffsetString(systemTimeZoneIdentifier) is true, then
  379. if (is_time_zone_offset_string(system_time_zone_identifier)) {
  380. // a. Let offsetNs be ParseTimeZoneOffsetString(systemTimeZoneIdentifier).
  381. offset_nanoseconds = parse_time_zone_offset_string(system_time_zone_identifier);
  382. }
  383. // 3. Else,
  384. else {
  385. // a. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, ℤ(ℝ(t) × 10^6)).
  386. auto offset = get_named_time_zone_offset_milliseconds(system_time_zone_identifier, time);
  387. offset_nanoseconds = static_cast<double>(offset.offset.to_nanoseconds());
  388. }
  389. // 4. Let offsetMs be truncate(offsetNs / 10^6).
  390. auto offset_milliseconds = trunc(offset_nanoseconds / 1e6);
  391. // 5. Return t + 𝔽(offsetMs).
  392. return time + offset_milliseconds;
  393. }
  394. // 21.4.1.26 UTC ( t ), https://tc39.es/ecma262/#sec-utc-t
  395. double utc_time(double time)
  396. {
  397. // 1. Let systemTimeZoneIdentifier be SystemTimeZoneIdentifier().
  398. auto system_time_zone_identifier = JS::system_time_zone_identifier();
  399. double offset_nanoseconds { 0 };
  400. // 2. If IsTimeZoneOffsetString(systemTimeZoneIdentifier) is true, then
  401. if (is_time_zone_offset_string(system_time_zone_identifier)) {
  402. // a. Let offsetNs be ParseTimeZoneOffsetString(systemTimeZoneIdentifier).
  403. offset_nanoseconds = parse_time_zone_offset_string(system_time_zone_identifier);
  404. }
  405. // 3. Else,
  406. else {
  407. // a. Let possibleInstants be GetNamedTimeZoneEpochNanoseconds(systemTimeZoneIdentifier, ℝ(YearFromTime(t)), ℝ(MonthFromTime(t)) + 1, ℝ(DateFromTime(t)), ℝ(HourFromTime(t)), ℝ(MinFromTime(t)), ℝ(SecFromTime(t)), ℝ(msFromTime(t)), 0, 0).
  408. 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);
  409. // 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.
  410. Crypto::SignedBigInteger disambiguated_instant;
  411. // c. If possibleInstants is not empty, then
  412. if (!possible_instants.is_empty()) {
  413. // i. Let disambiguatedInstant be possibleInstants[0].
  414. disambiguated_instant = move(possible_instants.first());
  415. }
  416. // d. Else,
  417. else {
  418. // 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).
  419. // 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).
  420. // iii. Let disambiguatedInstant be the last element of possibleInstantsBefore.
  421. // FIXME: This branch currently cannot be reached with our implementation, because LibUnicode does not handle skipped time points.
  422. // When GetNamedTimeZoneEpochNanoseconds is updated to use a LibUnicode API which does handle them, implement these steps.
  423. VERIFY_NOT_REACHED();
  424. }
  425. // e. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, disambiguatedInstant).
  426. auto offset = get_named_time_zone_offset_nanoseconds(system_time_zone_identifier, disambiguated_instant);
  427. offset_nanoseconds = static_cast<double>(offset.offset.to_nanoseconds());
  428. }
  429. // 4. Let offsetMs be truncate(offsetNs / 10^6).
  430. auto offset_milliseconds = trunc(offset_nanoseconds / 1e6);
  431. // 5. Return t - 𝔽(offsetMs).
  432. return time - offset_milliseconds;
  433. }
  434. // 21.4.1.27 MakeTime ( hour, min, sec, ms ), https://tc39.es/ecma262/#sec-maketime
  435. double make_time(double hour, double min, double sec, double ms)
  436. {
  437. // 1. If hour is not finite or min is not finite or sec is not finite or ms is not finite, return NaN.
  438. if (!isfinite(hour) || !isfinite(min) || !isfinite(sec) || !isfinite(ms))
  439. return NAN;
  440. // 2. Let h be 𝔽(! ToIntegerOrInfinity(hour)).
  441. auto h = to_integer_or_infinity(hour);
  442. // 3. Let m be 𝔽(! ToIntegerOrInfinity(min)).
  443. auto m = to_integer_or_infinity(min);
  444. // 4. Let s be 𝔽(! ToIntegerOrInfinity(sec)).
  445. auto s = to_integer_or_infinity(sec);
  446. // 5. Let milli be 𝔽(! ToIntegerOrInfinity(ms)).
  447. auto milli = to_integer_or_infinity(ms);
  448. // 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 +).
  449. // NOTE: C++ arithmetic abides by IEEE 754 rules
  450. auto t = ((h * ms_per_hour + m * ms_per_minute) + s * ms_per_second) + milli;
  451. // 7. Return t.
  452. return t;
  453. }
  454. // 21.4.1.28 MakeDay ( year, month, date ), https://tc39.es/ecma262/#sec-makeday
  455. double make_day(double year, double month, double date)
  456. {
  457. // 1. If year is not finite or month is not finite or date is not finite, return NaN.
  458. if (!isfinite(year) || !isfinite(month) || !isfinite(date))
  459. return NAN;
  460. // 2. Let y be 𝔽(! ToIntegerOrInfinity(year)).
  461. auto y = to_integer_or_infinity(year);
  462. // 3. Let m be 𝔽(! ToIntegerOrInfinity(month)).
  463. auto m = to_integer_or_infinity(month);
  464. // 4. Let dt be 𝔽(! ToIntegerOrInfinity(date)).
  465. auto dt = to_integer_or_infinity(date);
  466. // 5. Let ym be y + 𝔽(floor(ℝ(m) / 12)).
  467. auto ym = y + floor(m / 12);
  468. // 6. If ym is not finite, return NaN.
  469. if (!isfinite(ym))
  470. return NAN;
  471. // 7. Let mn be 𝔽(ℝ(m) modulo 12).
  472. auto mn = modulo(m, 12);
  473. // 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.
  474. if (!AK::is_within_range<int>(ym) || !AK::is_within_range<int>(mn + 1))
  475. return NAN;
  476. auto t = days_since_epoch(static_cast<int>(ym), static_cast<int>(mn) + 1, 1) * ms_per_day;
  477. // 9. Return Day(t) + dt - 1𝔽.
  478. return day(static_cast<double>(t)) + dt - 1;
  479. }
  480. // 21.4.1.29 MakeDate ( day, time ), https://tc39.es/ecma262/#sec-makedate
  481. double make_date(double day, double time)
  482. {
  483. // 1. If day is not finite or time is not finite, return NaN.
  484. if (!isfinite(day) || !isfinite(time))
  485. return NAN;
  486. // 2. Let tv be day × msPerDay + time.
  487. auto tv = day * ms_per_day + time;
  488. // 3. If tv is not finite, return NaN.
  489. if (!isfinite(tv))
  490. return NAN;
  491. // 4. Return tv.
  492. return tv;
  493. }
  494. // 21.4.1.31 TimeClip ( time ), https://tc39.es/ecma262/#sec-timeclip
  495. double time_clip(double time)
  496. {
  497. // 1. If time is not finite, return NaN.
  498. if (!isfinite(time))
  499. return NAN;
  500. // 2. If abs(ℝ(time)) > 8.64 × 10^15, return NaN.
  501. if (fabs(time) > 8.64E15)
  502. return NAN;
  503. // 3. Return 𝔽(! ToIntegerOrInfinity(time)).
  504. return to_integer_or_infinity(time);
  505. }
  506. // 21.4.1.33.1 IsTimeZoneOffsetString ( offsetString ), https://tc39.es/ecma262/#sec-istimezoneoffsetstring
  507. bool is_time_zone_offset_string(StringView offset_string)
  508. {
  509. // 1. Let parseResult be ParseText(StringToCodePoints(offsetString), UTCOffset).
  510. auto parse_result = Temporal::parse_iso8601(Temporal::Production::TimeZoneNumericUTCOffset, offset_string);
  511. // 2. If parseResult is a List of errors, return false.
  512. // 3. Return true.
  513. return parse_result.has_value();
  514. }
  515. // 21.4.1.33.2 ParseTimeZoneOffsetString ( offsetString ), https://tc39.es/ecma262/#sec-parsetimezoneoffsetstring
  516. double parse_time_zone_offset_string(StringView offset_string)
  517. {
  518. // 1. Let parseResult be ParseText(offsetString, UTCOffset).
  519. auto parse_result = Temporal::parse_iso8601(Temporal::Production::TimeZoneNumericUTCOffset, offset_string);
  520. // 2. Assert: parseResult is not a List of errors.
  521. VERIFY(parse_result.has_value());
  522. // 3. Assert: parseResult contains a ASCIISign Parse Node.
  523. VERIFY(parse_result->time_zone_utc_offset_sign.has_value());
  524. // 4. Let parsedSign be the source text matched by the ASCIISign Parse Node contained within parseResult.
  525. auto parsed_sign = *parse_result->time_zone_utc_offset_sign;
  526. i8 sign { 0 };
  527. // 5. If parsedSign is the single code point U+002D (HYPHEN-MINUS), then
  528. if (parsed_sign == "-"sv) {
  529. // a. Let sign be -1.
  530. sign = -1;
  531. }
  532. // 6. Else,
  533. else {
  534. // a. Let sign be 1.
  535. sign = 1;
  536. }
  537. // 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.
  538. // 8. Assert: parseResult contains an Hour Parse Node.
  539. VERIFY(parse_result->time_zone_utc_offset_hour.has_value());
  540. // 9. Let parsedHours be the source text matched by the Hour Parse Node contained within parseResult.
  541. auto parsed_hours = *parse_result->time_zone_utc_offset_hour;
  542. // 10. Let hours be ℝ(StringToNumber(CodePointsToString(parsedHours))).
  543. auto hours = string_to_number(parsed_hours);
  544. double minutes { 0 };
  545. double seconds { 0 };
  546. double nanoseconds { 0 };
  547. // 11. If parseResult does not contain a MinuteSecond Parse Node, then
  548. if (!parse_result->time_zone_utc_offset_minute.has_value()) {
  549. // a. Let minutes be 0.
  550. minutes = 0;
  551. }
  552. // 12. Else,
  553. else {
  554. // a. Let parsedMinutes be the source text matched by the first MinuteSecond Parse Node contained within parseResult.
  555. auto parsed_minutes = *parse_result->time_zone_utc_offset_minute;
  556. // b. Let minutes be ℝ(StringToNumber(CodePointsToString(parsedMinutes))).
  557. minutes = string_to_number(parsed_minutes);
  558. }
  559. // 13. If parseResult does not contain two MinuteSecond Parse Nodes, then
  560. if (!parse_result->time_zone_utc_offset_second.has_value()) {
  561. // a. Let seconds be 0.
  562. seconds = 0;
  563. }
  564. // 14. Else,
  565. else {
  566. // a. Let parsedSeconds be the source text matched by the second secondSecond Parse Node contained within parseResult.
  567. auto parsed_seconds = *parse_result->time_zone_utc_offset_second;
  568. // b. Let seconds be ℝ(StringToNumber(CodePointsToString(parsedSeconds))).
  569. seconds = string_to_number(parsed_seconds);
  570. }
  571. // 15. If parseResult does not contain a TemporalDecimalFraction Parse Node, then
  572. if (!parse_result->time_zone_utc_offset_fraction.has_value()) {
  573. // a. Let nanoseconds be 0.
  574. nanoseconds = 0;
  575. }
  576. // 16. Else,
  577. else {
  578. // a. Let parsedFraction be the source text matched by the TemporalDecimalFraction Parse Node contained within parseResult.
  579. auto parsed_fraction = *parse_result->time_zone_utc_offset_fraction;
  580. // b. Let fraction be the string-concatenation of CodePointsToString(parsedFraction) and "000000000".
  581. auto fraction = ByteString::formatted("{}000000000", parsed_fraction);
  582. // c. Let nanosecondsString be the substring of fraction from 1 to 10.
  583. auto nanoseconds_string = fraction.substring_view(1, 9);
  584. // d. Let nanoseconds be ℝ(StringToNumber(nanosecondsString)).
  585. nanoseconds = string_to_number(nanoseconds_string);
  586. }
  587. // 17. Return sign × (((hours × 60 + minutes) × 60 + seconds) × 10^9 + nanoseconds).
  588. // NOTE: Using scientific notation (1e9) ensures the result of this expression is a double,
  589. // which is important - otherwise it's all integers and the result overflows!
  590. return sign * (((hours * 60 + minutes) * 60 + seconds) * 1e9 + nanoseconds);
  591. }
  592. }