Date.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. /*
  2. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2022, 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. static Crypto::SignedBigInteger const s_one_billion_bigint { 1'000'000'000 };
  18. static Crypto::SignedBigInteger const s_one_million_bigint { 1'000'000 };
  19. static Crypto::SignedBigInteger const s_one_thousand_bigint { 1'000 };
  20. Date* Date::create(Realm& realm, double date_value)
  21. {
  22. return realm.heap().allocate<Date>(realm, date_value, *realm.intrinsics().date_prototype());
  23. }
  24. Date::Date(double date_value, Object& prototype)
  25. : Object(prototype)
  26. , m_date_value(date_value)
  27. {
  28. }
  29. String Date::iso_date_string() const
  30. {
  31. int year = year_from_time(m_date_value);
  32. StringBuilder builder;
  33. if (year < 0)
  34. builder.appendff("-{:06}", -year);
  35. else if (year > 9999)
  36. builder.appendff("+{:06}", year);
  37. else
  38. builder.appendff("{:04}", year);
  39. builder.append('-');
  40. builder.appendff("{:02}", month_from_time(m_date_value) + 1);
  41. builder.append('-');
  42. builder.appendff("{:02}", date_from_time(m_date_value));
  43. builder.append('T');
  44. builder.appendff("{:02}", hour_from_time(m_date_value));
  45. builder.append(':');
  46. builder.appendff("{:02}", min_from_time(m_date_value));
  47. builder.append(':');
  48. builder.appendff("{:02}", sec_from_time(m_date_value));
  49. builder.append('.');
  50. builder.appendff("{:03}", ms_from_time(m_date_value));
  51. builder.append('Z');
  52. return builder.build();
  53. }
  54. // DayWithinYear(t), https://tc39.es/ecma262/#eqn-DayWithinYear
  55. u16 day_within_year(double t)
  56. {
  57. if (!Value(t).is_finite_number())
  58. return 0;
  59. // Day(t) - DayFromYear(YearFromTime(t))
  60. return static_cast<u16>(day(t) - day_from_year(year_from_time(t)));
  61. }
  62. // DateFromTime(t), https://tc39.es/ecma262/#sec-date-number
  63. u8 date_from_time(double t)
  64. {
  65. switch (month_from_time(t)) {
  66. // DayWithinYear(t) + 1𝔽 if MonthFromTime(t) = +0𝔽
  67. case 0:
  68. return day_within_year(t) + 1;
  69. // DayWithinYear(t) - 30𝔽 if MonthFromTime(t) = 1𝔽
  70. case 1:
  71. return day_within_year(t) - 30;
  72. // DayWithinYear(t) - 58𝔽 - InLeapYear(t) if MonthFromTime(t) = 2𝔽
  73. case 2:
  74. return day_within_year(t) - 58 - in_leap_year(t);
  75. // DayWithinYear(t) - 89𝔽 - InLeapYear(t) if MonthFromTime(t) = 3𝔽
  76. case 3:
  77. return day_within_year(t) - 89 - in_leap_year(t);
  78. // DayWithinYear(t) - 119𝔽 - InLeapYear(t) if MonthFromTime(t) = 4𝔽
  79. case 4:
  80. return day_within_year(t) - 119 - in_leap_year(t);
  81. // DayWithinYear(t) - 150𝔽 - InLeapYear(t) if MonthFromTime(t) = 5𝔽
  82. case 5:
  83. return day_within_year(t) - 150 - in_leap_year(t);
  84. // DayWithinYear(t) - 180𝔽 - InLeapYear(t) if MonthFromTime(t) = 6𝔽
  85. case 6:
  86. return day_within_year(t) - 180 - in_leap_year(t);
  87. // DayWithinYear(t) - 211𝔽 - InLeapYear(t) if MonthFromTime(t) = 7𝔽
  88. case 7:
  89. return day_within_year(t) - 211 - in_leap_year(t);
  90. // DayWithinYear(t) - 242𝔽 - InLeapYear(t) if MonthFromTime(t) = 8𝔽
  91. case 8:
  92. return day_within_year(t) - 242 - in_leap_year(t);
  93. // DayWithinYear(t) - 272𝔽 - InLeapYear(t) if MonthFromTime(t) = 9𝔽
  94. case 9:
  95. return day_within_year(t) - 272 - in_leap_year(t);
  96. // DayWithinYear(t) - 303𝔽 - InLeapYear(t) if MonthFromTime(t) = 10𝔽
  97. case 10:
  98. return day_within_year(t) - 303 - in_leap_year(t);
  99. // DayWithinYear(t) - 333𝔽 - InLeapYear(t) if MonthFromTime(t) = 11𝔽
  100. case 11:
  101. return day_within_year(t) - 333 - in_leap_year(t);
  102. default:
  103. VERIFY_NOT_REACHED();
  104. }
  105. }
  106. // DaysInYear(y), https://tc39.es/ecma262/#eqn-DaysInYear
  107. u16 days_in_year(i32 y)
  108. {
  109. // 365𝔽 if (ℝ(y) modulo 4) ≠ 0
  110. if (y % 4 != 0)
  111. return 365;
  112. // 366𝔽 if (ℝ(y) modulo 4) = 0 and (ℝ(y) modulo 100) ≠ 0
  113. if (y % 4 == 0 && y % 100 != 0)
  114. return 366;
  115. // 365𝔽 if (ℝ(y) modulo 100) = 0 and (ℝ(y) modulo 400) ≠ 0
  116. if (y % 100 == 0 && y % 400 != 0)
  117. return 365;
  118. // 366𝔽 if (ℝ(y) modulo 400) = 0
  119. if (y % 400 == 0)
  120. return 366;
  121. VERIFY_NOT_REACHED();
  122. }
  123. // DayFromYear(y), https://tc39.es/ecma262/#eqn-DaysFromYear
  124. double day_from_year(i32 y)
  125. {
  126. // 𝔽(365 × (ℝ(y) - 1970) + floor((ℝ(y) - 1969) / 4) - floor((ℝ(y) - 1901) / 100) + floor((ℝ(y) - 1601) / 400))
  127. return 365.0 * (y - 1970) + floor((y - 1969) / 4.0) - floor((y - 1901) / 100.0) + floor((y - 1601) / 400.0);
  128. }
  129. // TimeFromYear(y), https://tc39.es/ecma262/#eqn-TimeFromYear
  130. double time_from_year(i32 y)
  131. {
  132. // msPerDay × DayFromYear(y)
  133. return ms_per_day * day_from_year(y);
  134. }
  135. // YearFromTime(t), https://tc39.es/ecma262/#eqn-YearFromTime
  136. i32 year_from_time(double t)
  137. {
  138. // the largest integral Number y (closest to +∞) such that TimeFromYear(y) ≤ t
  139. if (!Value(t).is_finite_number())
  140. return NumericLimits<i32>::max();
  141. // Approximation using average number of milliseconds per year. We might have to adjust this guess afterwards.
  142. auto year = static_cast<i32>(t / (365.2425 * ms_per_day) + 1970);
  143. auto year_t = time_from_year(year);
  144. if (year_t > t)
  145. year--;
  146. else if (year_t + days_in_year(year) * ms_per_day <= t)
  147. year++;
  148. return year;
  149. }
  150. // InLeapYear(t), https://tc39.es/ecma262/#eqn-InLeapYear
  151. bool in_leap_year(double t)
  152. {
  153. // +0𝔽 if DaysInYear(YearFromTime(t)) = 365𝔽
  154. // 1𝔽 if DaysInYear(YearFromTime(t)) = 366𝔽
  155. return days_in_year(year_from_time(t)) == 366;
  156. }
  157. // MonthFromTime(t), https://tc39.es/ecma262/#eqn-MonthFromTime
  158. u8 month_from_time(double t)
  159. {
  160. auto in_leap_year = JS::in_leap_year(t);
  161. auto day_within_year = JS::day_within_year(t);
  162. // +0𝔽 if +0𝔽 ≤ DayWithinYear(t) < 31𝔽
  163. if (day_within_year < 31)
  164. return 0;
  165. // 1𝔽 if 31𝔽 ≤ DayWithinYear(t) < 59𝔽 + InLeapYear(t)
  166. if (31 <= day_within_year && day_within_year < 59 + in_leap_year)
  167. return 1;
  168. // 2𝔽 if 59𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 90𝔽 + InLeapYear(t)
  169. if (59 + in_leap_year <= day_within_year && day_within_year < 90 + in_leap_year)
  170. return 2;
  171. // 3𝔽 if 90𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 120𝔽 + InLeapYear(t)
  172. if (90 + in_leap_year <= day_within_year && day_within_year < 120 + in_leap_year)
  173. return 3;
  174. // 4𝔽 if 120𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 151𝔽 + InLeapYear(t)
  175. if (120 + in_leap_year <= day_within_year && day_within_year < 151 + in_leap_year)
  176. return 4;
  177. // 5𝔽 if 151𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 181𝔽 + InLeapYear(t)
  178. if (151 + in_leap_year <= day_within_year && day_within_year < 181 + in_leap_year)
  179. return 5;
  180. // 6𝔽 if 181𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 212𝔽 + InLeapYear(t)
  181. if (181 + in_leap_year <= day_within_year && day_within_year < 212 + in_leap_year)
  182. return 6;
  183. // 7𝔽 if 212𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 243𝔽 + InLeapYear(t)
  184. if (212 + in_leap_year <= day_within_year && day_within_year < 243 + in_leap_year)
  185. return 7;
  186. // 8𝔽 if 243𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 273𝔽 + InLeapYear(t)
  187. if (243 + in_leap_year <= day_within_year && day_within_year < 273 + in_leap_year)
  188. return 8;
  189. // 9𝔽 if 273𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 304𝔽 + InLeapYear(t)
  190. if (273 + in_leap_year <= day_within_year && day_within_year < 304 + in_leap_year)
  191. return 9;
  192. // 10𝔽 if 304𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 334𝔽 + InLeapYear(t)
  193. if (304 + in_leap_year <= day_within_year && day_within_year < 334 + in_leap_year)
  194. return 10;
  195. // 11𝔽 if 334𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 365𝔽 + InLeapYear(t)
  196. if (334 + in_leap_year <= day_within_year && day_within_year < 365 + in_leap_year)
  197. return 11;
  198. VERIFY_NOT_REACHED();
  199. }
  200. // HourFromTime(t), https://tc39.es/ecma262/#eqn-HourFromTime
  201. u8 hour_from_time(double t)
  202. {
  203. if (!Value(t).is_finite_number())
  204. return 0;
  205. // 𝔽(floor(ℝ(t / msPerHour)) modulo HoursPerDay)
  206. return static_cast<u8>(modulo(floor(t / ms_per_hour), hours_per_day));
  207. }
  208. // MinFromTime(t), https://tc39.es/ecma262/#eqn-MinFromTime
  209. u8 min_from_time(double t)
  210. {
  211. if (!Value(t).is_finite_number())
  212. return 0;
  213. // 𝔽(floor(ℝ(t / msPerMinute)) modulo MinutesPerHour)
  214. return static_cast<u8>(modulo(floor(t / ms_per_minute), minutes_per_hour));
  215. }
  216. // SecFromTime(t), https://tc39.es/ecma262/#eqn-SecFromTime
  217. u8 sec_from_time(double t)
  218. {
  219. if (!Value(t).is_finite_number())
  220. return 0;
  221. // 𝔽(floor(ℝ(t / msPerSecond)) modulo SecondsPerMinute)
  222. return static_cast<u8>(modulo(floor(t / ms_per_second), seconds_per_minute));
  223. }
  224. // msFromTime(t), https://tc39.es/ecma262/#eqn-msFromTime
  225. u16 ms_from_time(double t)
  226. {
  227. if (!Value(t).is_finite_number())
  228. return 0;
  229. // 𝔽(ℝ(t) modulo ℝ(msPerSecond))
  230. return static_cast<u16>(modulo(t, ms_per_second));
  231. }
  232. // 21.4.1.6 Week Day, https://tc39.es/ecma262/#sec-week-day
  233. u8 week_day(double t)
  234. {
  235. if (!Value(t).is_finite_number())
  236. return 0;
  237. // 𝔽(ℝ(Day(t) + 4𝔽) modulo 7)
  238. return static_cast<u8>(modulo(day(t) + 4, 7));
  239. }
  240. // 21.4.1.7 LocalTZA ( t, isUTC ), https://tc39.es/ecma262/#sec-local-time-zone-adjustment
  241. // FIXME: Remove this when ECMA-402 is synced with https://github.com/tc39/ecma262/commit/43fd5f25357333d8340bfb486b8f0738e6d0d0cb.
  242. double local_tza(double time, [[maybe_unused]] bool is_utc, Optional<StringView> time_zone_override)
  243. {
  244. // The time_zone_override parameter is non-standard, but allows callers to override the system
  245. // time zone with a specific value without setting environment variables.
  246. auto time_zone = time_zone_override.value_or(TimeZone::current_time_zone());
  247. // When isUTC is true, LocalTZA( tUTC, true ) should return the offset of the local time zone from
  248. // UTC measured in milliseconds at time represented by time value tUTC. When the result is added to
  249. // tUTC, it should yield the corresponding Number tlocal.
  250. // When isUTC is false, LocalTZA( tlocal, false ) should return the offset of the local time zone from
  251. // UTC measured in milliseconds at local time represented by Number tlocal. When the result is subtracted
  252. // from tlocal, it should yield the corresponding time value tUTC.
  253. auto time_since_epoch = Value(time).is_finite_number() ? AK::Time::from_milliseconds(time) : AK::Time::max();
  254. auto maybe_offset = TimeZone::get_time_zone_offset(time_zone, time_since_epoch);
  255. return maybe_offset.has_value() ? static_cast<double>(maybe_offset->seconds) * 1000 : 0;
  256. }
  257. // 21.4.1.7 GetUTCEpochNanoseconds ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/ecma262/#sec-getutcepochnanoseconds
  258. Crypto::SignedBigInteger get_utc_epoch_nanoseconds(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond)
  259. {
  260. // 1. Let date be MakeDay(𝔽(year), 𝔽(month - 1), 𝔽(day)).
  261. auto date = make_day(year, month - 1, day);
  262. // 2. Let time be MakeTime(𝔽(hour), 𝔽(minute), 𝔽(second), 𝔽(millisecond)).
  263. auto time = make_time(hour, minute, second, millisecond);
  264. // 3. Let ms be MakeDate(date, time).
  265. auto ms = make_date(date, time);
  266. // 4. Assert: ms is an integral Number.
  267. VERIFY(ms == trunc(ms));
  268. // 5. Return ℤ(ℝ(ms) × 10^6 + microsecond × 10^3 + nanosecond).
  269. auto result = Crypto::SignedBigInteger { ms }.multiplied_by(s_one_million_bigint);
  270. result = result.plus(Crypto::SignedBigInteger { static_cast<i32>(microsecond) }.multiplied_by(s_one_thousand_bigint));
  271. result = result.plus(Crypto::SignedBigInteger { static_cast<i32>(nanosecond) });
  272. return result;
  273. }
  274. static i64 clip_bigint_to_sane_time(Crypto::SignedBigInteger const& value)
  275. {
  276. static Crypto::SignedBigInteger const min_bigint { NumericLimits<i64>::min() };
  277. static Crypto::SignedBigInteger const max_bigint { NumericLimits<i64>::max() };
  278. // The provided epoch (nano)seconds value is potentially out of range for AK::Time and subsequently
  279. // get_time_zone_offset(). We can safely assume that the TZDB has no useful information that far
  280. // into the past and future anyway, so clamp it to the i64 range.
  281. if (value < min_bigint)
  282. return NumericLimits<i64>::min();
  283. if (value > max_bigint)
  284. return NumericLimits<i64>::max();
  285. // FIXME: Can we do this without string conversion?
  286. return value.to_base(10).to_int<i64>().value();
  287. }
  288. // 21.4.1.8 GetNamedTimeZoneEpochNanoseconds ( timeZoneIdentifier, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/ecma262/#sec-getnamedtimezoneepochnanoseconds
  289. 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)
  290. {
  291. auto local_nanoseconds = get_utc_epoch_nanoseconds(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond);
  292. auto local_time = Time::from_nanoseconds(clip_bigint_to_sane_time(local_nanoseconds));
  293. // FIXME: LibTimeZone does not behave exactly as the spec expects. It does not consider repeated or skipped time points.
  294. auto offset = TimeZone::get_time_zone_offset(time_zone_identifier, local_time);
  295. // Can only fail if the time zone identifier is invalid, which cannot be the case here.
  296. VERIFY(offset.has_value());
  297. return { local_nanoseconds.minus(Crypto::SignedBigInteger { offset->seconds }.multiplied_by(s_one_billion_bigint)) };
  298. }
  299. // 21.4.1.9 GetNamedTimeZoneOffsetNanoseconds ( timeZoneIdentifier, epochNanoseconds ), https://tc39.es/ecma262/#sec-getnamedtimezoneoffsetnanoseconds
  300. i64 get_named_time_zone_offset_nanoseconds(StringView time_zone_identifier, Crypto::SignedBigInteger const& epoch_nanoseconds)
  301. {
  302. // Only called with validated time zone identifier as argument.
  303. auto time_zone = TimeZone::time_zone_from_string(time_zone_identifier);
  304. VERIFY(time_zone.has_value());
  305. // Since Time::from_seconds() and Time::from_nanoseconds() both take an i64, converting to
  306. // seconds first gives us a greater range. The TZDB doesn't have sub-second offsets.
  307. auto seconds = epoch_nanoseconds.divided_by(s_one_billion_bigint).quotient;
  308. auto time = Time::from_seconds(clip_bigint_to_sane_time(seconds));
  309. auto offset = TimeZone::get_time_zone_offset(*time_zone, time);
  310. VERIFY(offset.has_value());
  311. return offset->seconds * 1'000'000'000;
  312. }
  313. // 21.4.1.10 DefaultTimeZone ( ), https://tc39.es/ecma262/#sec-defaulttimezone
  314. StringView default_time_zone()
  315. {
  316. return TimeZone::current_time_zone();
  317. }
  318. // 21.4.1.11 LocalTime ( t ), https://tc39.es/ecma262/#sec-localtime
  319. double local_time(double time)
  320. {
  321. // 1. Let localTimeZone be DefaultTimeZone().
  322. auto local_time_zone = default_time_zone();
  323. double offset_nanoseconds { 0 };
  324. // 2. If IsTimeZoneOffsetString(localTimeZone) is true, then
  325. if (is_time_zone_offset_string(local_time_zone)) {
  326. // a. Let offsetNs be ParseTimeZoneOffsetString(localTimeZone).
  327. offset_nanoseconds = parse_time_zone_offset_string(local_time_zone);
  328. }
  329. // 3. Else,
  330. else {
  331. // a. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(localTimeZone, ℤ(ℝ(t) × 10^6)).
  332. auto time_bigint = Crypto::SignedBigInteger { time }.multiplied_by(s_one_million_bigint);
  333. offset_nanoseconds = get_named_time_zone_offset_nanoseconds(local_time_zone, time_bigint);
  334. }
  335. // 4. Let offsetMs be truncate(offsetNs / 10^6).
  336. auto offset_milliseconds = trunc(offset_nanoseconds / 1e6);
  337. // 5. Return t + 𝔽(offsetMs).
  338. return time + offset_milliseconds;
  339. }
  340. // 21.4.1.12 UTC ( t ), https://tc39.es/ecma262/#sec-utc-t
  341. double utc_time(double time)
  342. {
  343. // 1. Let localTimeZone be DefaultTimeZone().
  344. auto local_time_zone = default_time_zone();
  345. double offset_nanoseconds { 0 };
  346. // 2. If IsTimeZoneOffsetString(localTimeZone) is true, then
  347. if (is_time_zone_offset_string(local_time_zone)) {
  348. // a. Let offsetNs be ParseTimeZoneOffsetString(localTimeZone).
  349. offset_nanoseconds = parse_time_zone_offset_string(local_time_zone);
  350. }
  351. // 3. Else,
  352. else {
  353. // a. Let possibleInstants be GetNamedTimeZoneEpochNanoseconds(localTimeZone, ℝ(YearFromTime(t)), ℝ(MonthFromTime(t)) + 1, ℝ(DateFromTime(t)), ℝ(HourFromTime(t)), ℝ(MinFromTime(t)), ℝ(SecFromTime(t)), ℝ(msFromTime(t)), 0, 0).
  354. auto possible_instants = get_named_time_zone_epoch_nanoseconds(local_time_zone, 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);
  355. // 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.
  356. Crypto::SignedBigInteger disambiguated_instant;
  357. // c. If possibleInstants is not empty, then
  358. if (!possible_instants.is_empty()) {
  359. // i. Let disambiguatedInstant be possibleInstants[0].
  360. disambiguated_instant = move(possible_instants.first());
  361. }
  362. // d. Else,
  363. else {
  364. // 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).
  365. // ii. Let possibleInstantsBefore be GetNamedTimeZoneEpochNanoseconds(localTimeZone, ℝ(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).
  366. // iii. Let disambiguatedInstant be the last element of possibleInstantsBefore.
  367. // FIXME: This branch currently cannot be reached with our implementation, because LibTimeZone does not handle skipped time points.
  368. // When GetNamedTimeZoneEpochNanoseconds is updated to use a LibTimeZone API which does handle them, implement these steps.
  369. VERIFY_NOT_REACHED();
  370. }
  371. // e. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(localTimeZone, disambiguatedInstant).
  372. offset_nanoseconds = get_named_time_zone_offset_nanoseconds(local_time_zone, disambiguated_instant);
  373. }
  374. // 4. Let offsetMs be truncate(offsetNs / 10^6).
  375. auto offset_milliseconds = trunc(offset_nanoseconds / 1e6);
  376. // 5. Return t - 𝔽(offsetMs).
  377. return time - offset_milliseconds;
  378. }
  379. // 21.4.1.14 MakeTime ( hour, min, sec, ms ), https://tc39.es/ecma262/#sec-maketime
  380. double make_time(double hour, double min, double sec, double ms)
  381. {
  382. // 1. If hour is not finite or min is not finite or sec is not finite or ms is not finite, return NaN.
  383. if (!isfinite(hour) || !isfinite(min) || !isfinite(sec) || !isfinite(ms))
  384. return NAN;
  385. // 2. Let h be 𝔽(! ToIntegerOrInfinity(hour)).
  386. auto h = to_integer_or_infinity(hour);
  387. // 3. Let m be 𝔽(! ToIntegerOrInfinity(min)).
  388. auto m = to_integer_or_infinity(min);
  389. // 4. Let s be 𝔽(! ToIntegerOrInfinity(sec)).
  390. auto s = to_integer_or_infinity(sec);
  391. // 5. Let milli be 𝔽(! ToIntegerOrInfinity(ms)).
  392. auto milli = to_integer_or_infinity(ms);
  393. // 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 +).
  394. // NOTE: C++ arithmetic abides by IEEE 754 rules
  395. auto t = ((h * ms_per_hour + m * ms_per_minute) + s * ms_per_second) + milli;
  396. // 7. Return t.
  397. return t;
  398. }
  399. // Day(t), https://tc39.es/ecma262/#eqn-Day
  400. double day(double time_value)
  401. {
  402. return floor(time_value / ms_per_day);
  403. }
  404. // TimeWithinDay(t), https://tc39.es/ecma262/#eqn-TimeWithinDay
  405. double time_within_day(double time)
  406. {
  407. // 𝔽(ℝ(t) modulo ℝ(msPerDay))
  408. return modulo(time, ms_per_day);
  409. }
  410. // 21.4.1.15 MakeDay ( year, month, date ), https://tc39.es/ecma262/#sec-makeday
  411. double make_day(double year, double month, double date)
  412. {
  413. // 1. If year is not finite or month is not finite or date is not finite, return NaN.
  414. if (!isfinite(year) || !isfinite(month) || !isfinite(date))
  415. return NAN;
  416. // 2. Let y be 𝔽(! ToIntegerOrInfinity(year)).
  417. auto y = to_integer_or_infinity(year);
  418. // 3. Let m be 𝔽(! ToIntegerOrInfinity(month)).
  419. auto m = to_integer_or_infinity(month);
  420. // 4. Let dt be 𝔽(! ToIntegerOrInfinity(date)).
  421. auto dt = to_integer_or_infinity(date);
  422. // 5. Let ym be y + 𝔽(floor(ℝ(m) / 12)).
  423. auto ym = y + floor(m / 12);
  424. // 6. If ym is not finite, return NaN.
  425. if (!isfinite(ym))
  426. return NAN;
  427. // 7. Let mn be 𝔽(ℝ(m) modulo 12).
  428. auto mn = modulo(m, 12);
  429. // 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.
  430. if (!AK::is_within_range<int>(ym) || !AK::is_within_range<int>(mn + 1))
  431. return NAN;
  432. // FIXME: We are avoiding AK::years_to_days_since_epoch here because it is implemented by looping over
  433. // the range [1970, ym), which will spin for any time value with an extremely large year.
  434. auto t = time_from_year(ym) + (day_of_year(static_cast<int>(ym), static_cast<int>(mn) + 1, 1) * ms_per_day);
  435. // 9. Return Day(t) + dt - 1𝔽.
  436. return day(static_cast<double>(t)) + dt - 1;
  437. }
  438. // 21.4.1.16 MakeDate ( day, time ), https://tc39.es/ecma262/#sec-makedate
  439. double make_date(double day, double time)
  440. {
  441. // 1. If day is not finite or time is not finite, return NaN.
  442. if (!isfinite(day) || !isfinite(time))
  443. return NAN;
  444. // 2. Let tv be day × msPerDay + time.
  445. auto tv = day * ms_per_day + time;
  446. // 3. If tv is not finite, return NaN.
  447. if (!isfinite(tv))
  448. return NAN;
  449. // 4. Return tv.
  450. return tv;
  451. }
  452. // 21.4.1.17 TimeClip ( time ), https://tc39.es/ecma262/#sec-timeclip
  453. double time_clip(double time)
  454. {
  455. // 1. If time is not finite, return NaN.
  456. if (!isfinite(time))
  457. return NAN;
  458. // 2. If abs(ℝ(time)) > 8.64 × 10^15, return NaN.
  459. if (fabs(time) > 8.64E15)
  460. return NAN;
  461. // 3. Return 𝔽(! ToIntegerOrInfinity(time)).
  462. return to_integer_or_infinity(time);
  463. }
  464. // 21.4.1.19.1 IsTimeZoneOffsetString ( offsetString ), https://tc39.es/ecma262/#sec-istimezoneoffsetstring
  465. bool is_time_zone_offset_string(StringView offset_string)
  466. {
  467. // 1. Let parseResult be ParseText(StringToCodePoints(offsetString), UTCOffset).
  468. auto parse_result = Temporal::parse_iso8601(Temporal::Production::TimeZoneNumericUTCOffset, offset_string);
  469. // 2. If parseResult is a List of errors, return false.
  470. // 3. Return true.
  471. return parse_result.has_value();
  472. }
  473. // 21.4.1.19.2 ParseTimeZoneOffsetString ( offsetString ), https://tc39.es/ecma262/#sec-parsetimezoneoffsetstring
  474. double parse_time_zone_offset_string(StringView offset_string)
  475. {
  476. // 1. Let parseResult be ParseText(StringToCodePoints(offsetString), UTCOffset).
  477. auto parse_result = Temporal::parse_iso8601(Temporal::Production::TimeZoneNumericUTCOffset, offset_string);
  478. // 2. Assert: parseResult is not a List of errors.
  479. VERIFY(parse_result.has_value());
  480. // 3. Assert: parseResult contains a TemporalSign Parse Node.
  481. VERIFY(parse_result->time_zone_utc_offset_sign.has_value());
  482. // 4. Let parsedSign be the source text matched by the TemporalSign Parse Node contained within parseResult.
  483. auto parsed_sign = *parse_result->time_zone_utc_offset_sign;
  484. i8 sign { 0 };
  485. // 5. If parsedSign is the single code point U+002D (HYPHEN-MINUS) or U+2212 (MINUS SIGN), then
  486. if (parsed_sign.is_one_of("-"sv, "\xE2\x88\x92"sv)) {
  487. // a. Let sign be -1.
  488. sign = -1;
  489. }
  490. // 6. Else,
  491. else {
  492. // a. Let sign be 1.
  493. sign = 1;
  494. }
  495. // 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.
  496. // 8. Assert: parseResult contains an Hour Parse Node.
  497. VERIFY(parse_result->time_zone_utc_offset_hour.has_value());
  498. // 9. Let parsedHours be the source text matched by the Hour Parse Node contained within parseResult.
  499. auto parsed_hours = *parse_result->time_zone_utc_offset_hour;
  500. // 10. Let hours be ℝ(StringToNumber(CodePointsToString(parsedHours))).
  501. auto hours = string_to_number(parsed_hours)->as_double();
  502. double minutes { 0 };
  503. double seconds { 0 };
  504. double nanoseconds { 0 };
  505. // 11. If parseResult does not contain a MinuteSecond Parse Node, then
  506. if (!parse_result->time_zone_utc_offset_minute.has_value()) {
  507. // a. Let minutes be 0.
  508. minutes = 0;
  509. }
  510. // 12. Else,
  511. else {
  512. // a. Let parsedMinutes be the source text matched by the first MinuteSecond Parse Node contained within parseResult.
  513. auto parsed_minutes = *parse_result->time_zone_utc_offset_minute;
  514. // b. Let minutes be ℝ(StringToNumber(CodePointsToString(parsedMinutes))).
  515. minutes = string_to_number(parsed_minutes)->as_double();
  516. }
  517. // 13. If parseResult does not contain two MinuteSecond Parse Nodes, then
  518. if (!parse_result->time_zone_utc_offset_second.has_value()) {
  519. // a. Let seconds be 0.
  520. seconds = 0;
  521. }
  522. // 14. Else,
  523. else {
  524. // a. Let parsedSeconds be the source text matched by the second secondSecond Parse Node contained within parseResult.
  525. auto parsed_seconds = *parse_result->time_zone_utc_offset_second;
  526. // b. Let seconds be ℝ(StringToNumber(CodePointsToString(parsedSeconds))).
  527. seconds = string_to_number(parsed_seconds)->as_double();
  528. }
  529. // 15. If parseResult does not contain a TemporalDecimalFraction Parse Node, then
  530. if (!parse_result->time_zone_utc_offset_fraction.has_value()) {
  531. // a. Let nanoseconds be 0.
  532. nanoseconds = 0;
  533. }
  534. // 16. Else,
  535. else {
  536. // a. Let parsedFraction be the source text matched by the TemporalDecimalFraction Parse Node contained within parseResult.
  537. auto parsed_fraction = *parse_result->time_zone_utc_offset_fraction;
  538. // b. Let fraction be the string-concatenation of CodePointsToString(parsedFraction) and "000000000".
  539. auto fraction = String::formatted("{}000000000", parsed_fraction);
  540. // c. Let nanosecondsString be the substring of fraction from 1 to 10.
  541. auto nanoseconds_string = fraction.substring_view(1, 9);
  542. // d. Let nanoseconds be ℝ(StringToNumber(nanosecondsString)).
  543. nanoseconds = string_to_number(nanoseconds_string)->as_double();
  544. }
  545. // 17. Return sign × (((hours × 60 + minutes) × 60 + seconds) × 10^9 + nanoseconds).
  546. // NOTE: Using scientific notation (1e9) ensures the result of this expression is a double,
  547. // which is important - otherwise it's all integers and the result overflows!
  548. return sign * (((hours * 60 + minutes) * 60 + seconds) * 1e9 + nanoseconds);
  549. }
  550. }