Date.cpp 26 KB

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