Date.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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 GetUTCEpochNanoseconds ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/ecma262/#sec-getutcepochnanoseconds
  241. Crypto::SignedBigInteger get_utc_epoch_nanoseconds(i32 year, u8 month, u8 day, u8 hour, u8 minute, u8 second, u16 millisecond, u16 microsecond, u16 nanosecond)
  242. {
  243. // 1. Let date be MakeDay(๐”ฝ(year), ๐”ฝ(month - 1), ๐”ฝ(day)).
  244. auto date = make_day(year, month - 1, day);
  245. // 2. Let time be MakeTime(๐”ฝ(hour), ๐”ฝ(minute), ๐”ฝ(second), ๐”ฝ(millisecond)).
  246. auto time = make_time(hour, minute, second, millisecond);
  247. // 3. Let ms be MakeDate(date, time).
  248. auto ms = make_date(date, time);
  249. // 4. Assert: ms is an integral Number.
  250. VERIFY(ms == trunc(ms));
  251. // 5. Return โ„ค(โ„(ms) ร— 10^6 + microsecond ร— 10^3 + nanosecond).
  252. auto result = Crypto::SignedBigInteger { ms }.multiplied_by(s_one_million_bigint);
  253. result = result.plus(Crypto::SignedBigInteger { static_cast<i32>(microsecond) }.multiplied_by(s_one_thousand_bigint));
  254. result = result.plus(Crypto::SignedBigInteger { static_cast<i32>(nanosecond) });
  255. return result;
  256. }
  257. static i64 clip_bigint_to_sane_time(Crypto::SignedBigInteger const& value)
  258. {
  259. static Crypto::SignedBigInteger const min_bigint { NumericLimits<i64>::min() };
  260. static Crypto::SignedBigInteger const max_bigint { NumericLimits<i64>::max() };
  261. // The provided epoch (nano)seconds value is potentially out of range for AK::Time and subsequently
  262. // get_time_zone_offset(). We can safely assume that the TZDB has no useful information that far
  263. // into the past and future anyway, so clamp it to the i64 range.
  264. if (value < min_bigint)
  265. return NumericLimits<i64>::min();
  266. if (value > max_bigint)
  267. return NumericLimits<i64>::max();
  268. // FIXME: Can we do this without string conversion?
  269. return value.to_base(10).to_int<i64>().value();
  270. }
  271. // 21.4.1.8 GetNamedTimeZoneEpochNanoseconds ( timeZoneIdentifier, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond ), https://tc39.es/ecma262/#sec-getnamedtimezoneepochnanoseconds
  272. 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)
  273. {
  274. auto local_nanoseconds = get_utc_epoch_nanoseconds(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond);
  275. auto local_time = Time::from_nanoseconds(clip_bigint_to_sane_time(local_nanoseconds));
  276. // FIXME: LibTimeZone does not behave exactly as the spec expects. It does not consider repeated or skipped time points.
  277. auto offset = TimeZone::get_time_zone_offset(time_zone_identifier, local_time);
  278. // Can only fail if the time zone identifier is invalid, which cannot be the case here.
  279. VERIFY(offset.has_value());
  280. return { local_nanoseconds.minus(Crypto::SignedBigInteger { offset->seconds }.multiplied_by(s_one_billion_bigint)) };
  281. }
  282. // 21.4.1.9 GetNamedTimeZoneOffsetNanoseconds ( timeZoneIdentifier, epochNanoseconds ), https://tc39.es/ecma262/#sec-getnamedtimezoneoffsetnanoseconds
  283. i64 get_named_time_zone_offset_nanoseconds(StringView time_zone_identifier, Crypto::SignedBigInteger const& epoch_nanoseconds)
  284. {
  285. // Only called with validated time zone identifier as argument.
  286. auto time_zone = TimeZone::time_zone_from_string(time_zone_identifier);
  287. VERIFY(time_zone.has_value());
  288. // Since Time::from_seconds() and Time::from_nanoseconds() both take an i64, converting to
  289. // seconds first gives us a greater range. The TZDB doesn't have sub-second offsets.
  290. auto seconds = epoch_nanoseconds.divided_by(s_one_billion_bigint).quotient;
  291. auto time = Time::from_seconds(clip_bigint_to_sane_time(seconds));
  292. auto offset = TimeZone::get_time_zone_offset(*time_zone, time);
  293. VERIFY(offset.has_value());
  294. return offset->seconds * 1'000'000'000;
  295. }
  296. // 21.4.1.10 DefaultTimeZone ( ), https://tc39.es/ecma262/#sec-defaulttimezone
  297. // 6.4.3 DefaultTimeZone ( ), https://tc39.es/ecma402/#sup-defaulttimezone
  298. StringView default_time_zone()
  299. {
  300. return TimeZone::current_time_zone();
  301. }
  302. // 21.4.1.11 LocalTime ( t ), https://tc39.es/ecma262/#sec-localtime
  303. double local_time(double time)
  304. {
  305. // 1. Let localTimeZone be DefaultTimeZone().
  306. auto local_time_zone = default_time_zone();
  307. double offset_nanoseconds { 0 };
  308. // 2. If IsTimeZoneOffsetString(localTimeZone) is true, then
  309. if (is_time_zone_offset_string(local_time_zone)) {
  310. // a. Let offsetNs be ParseTimeZoneOffsetString(localTimeZone).
  311. offset_nanoseconds = parse_time_zone_offset_string(local_time_zone);
  312. }
  313. // 3. Else,
  314. else {
  315. // a. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(localTimeZone, โ„ค(โ„(t) ร— 10^6)).
  316. auto time_bigint = Crypto::SignedBigInteger { time }.multiplied_by(s_one_million_bigint);
  317. offset_nanoseconds = get_named_time_zone_offset_nanoseconds(local_time_zone, time_bigint);
  318. }
  319. // 4. Let offsetMs be truncate(offsetNs / 10^6).
  320. auto offset_milliseconds = trunc(offset_nanoseconds / 1e6);
  321. // 5. Return t + ๐”ฝ(offsetMs).
  322. return time + offset_milliseconds;
  323. }
  324. // 21.4.1.12 UTC ( t ), https://tc39.es/ecma262/#sec-utc-t
  325. double utc_time(double time)
  326. {
  327. // 1. Let localTimeZone be DefaultTimeZone().
  328. auto local_time_zone = default_time_zone();
  329. double offset_nanoseconds { 0 };
  330. // 2. If IsTimeZoneOffsetString(localTimeZone) is true, then
  331. if (is_time_zone_offset_string(local_time_zone)) {
  332. // a. Let offsetNs be ParseTimeZoneOffsetString(localTimeZone).
  333. offset_nanoseconds = parse_time_zone_offset_string(local_time_zone);
  334. }
  335. // 3. Else,
  336. else {
  337. // a. Let possibleInstants be GetNamedTimeZoneEpochNanoseconds(localTimeZone, โ„(YearFromTime(t)), โ„(MonthFromTime(t)) + 1, โ„(DateFromTime(t)), โ„(HourFromTime(t)), โ„(MinFromTime(t)), โ„(SecFromTime(t)), โ„(msFromTime(t)), 0, 0).
  338. 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);
  339. // 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.
  340. Crypto::SignedBigInteger disambiguated_instant;
  341. // c. If possibleInstants is not empty, then
  342. if (!possible_instants.is_empty()) {
  343. // i. Let disambiguatedInstant be possibleInstants[0].
  344. disambiguated_instant = move(possible_instants.first());
  345. }
  346. // d. Else,
  347. else {
  348. // 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).
  349. // 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).
  350. // iii. Let disambiguatedInstant be the last element of possibleInstantsBefore.
  351. // FIXME: This branch currently cannot be reached with our implementation, because LibTimeZone does not handle skipped time points.
  352. // When GetNamedTimeZoneEpochNanoseconds is updated to use a LibTimeZone API which does handle them, implement these steps.
  353. VERIFY_NOT_REACHED();
  354. }
  355. // e. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(localTimeZone, disambiguatedInstant).
  356. offset_nanoseconds = get_named_time_zone_offset_nanoseconds(local_time_zone, disambiguated_instant);
  357. }
  358. // 4. Let offsetMs be truncate(offsetNs / 10^6).
  359. auto offset_milliseconds = trunc(offset_nanoseconds / 1e6);
  360. // 5. Return t - ๐”ฝ(offsetMs).
  361. return time - offset_milliseconds;
  362. }
  363. // 21.4.1.14 MakeTime ( hour, min, sec, ms ), https://tc39.es/ecma262/#sec-maketime
  364. double make_time(double hour, double min, double sec, double ms)
  365. {
  366. // 1. If hour is not finite or min is not finite or sec is not finite or ms is not finite, return NaN.
  367. if (!isfinite(hour) || !isfinite(min) || !isfinite(sec) || !isfinite(ms))
  368. return NAN;
  369. // 2. Let h be ๐”ฝ(! ToIntegerOrInfinity(hour)).
  370. auto h = to_integer_or_infinity(hour);
  371. // 3. Let m be ๐”ฝ(! ToIntegerOrInfinity(min)).
  372. auto m = to_integer_or_infinity(min);
  373. // 4. Let s be ๐”ฝ(! ToIntegerOrInfinity(sec)).
  374. auto s = to_integer_or_infinity(sec);
  375. // 5. Let milli be ๐”ฝ(! ToIntegerOrInfinity(ms)).
  376. auto milli = to_integer_or_infinity(ms);
  377. // 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 +).
  378. // NOTE: C++ arithmetic abides by IEEE 754 rules
  379. auto t = ((h * ms_per_hour + m * ms_per_minute) + s * ms_per_second) + milli;
  380. // 7. Return t.
  381. return t;
  382. }
  383. // Day(t), https://tc39.es/ecma262/#eqn-Day
  384. double day(double time_value)
  385. {
  386. return floor(time_value / ms_per_day);
  387. }
  388. // TimeWithinDay(t), https://tc39.es/ecma262/#eqn-TimeWithinDay
  389. double time_within_day(double time)
  390. {
  391. // ๐”ฝ(โ„(t) modulo โ„(msPerDay))
  392. return modulo(time, ms_per_day);
  393. }
  394. // 21.4.1.15 MakeDay ( year, month, date ), https://tc39.es/ecma262/#sec-makeday
  395. double make_day(double year, double month, double date)
  396. {
  397. // 1. If year is not finite or month is not finite or date is not finite, return NaN.
  398. if (!isfinite(year) || !isfinite(month) || !isfinite(date))
  399. return NAN;
  400. // 2. Let y be ๐”ฝ(! ToIntegerOrInfinity(year)).
  401. auto y = to_integer_or_infinity(year);
  402. // 3. Let m be ๐”ฝ(! ToIntegerOrInfinity(month)).
  403. auto m = to_integer_or_infinity(month);
  404. // 4. Let dt be ๐”ฝ(! ToIntegerOrInfinity(date)).
  405. auto dt = to_integer_or_infinity(date);
  406. // 5. Let ym be y + ๐”ฝ(floor(โ„(m) / 12)).
  407. auto ym = y + floor(m / 12);
  408. // 6. If ym is not finite, return NaN.
  409. if (!isfinite(ym))
  410. return NAN;
  411. // 7. Let mn be ๐”ฝ(โ„(m) modulo 12).
  412. auto mn = modulo(m, 12);
  413. // 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.
  414. if (!AK::is_within_range<int>(ym) || !AK::is_within_range<int>(mn + 1))
  415. return NAN;
  416. // FIXME: We are avoiding AK::years_to_days_since_epoch here because it is implemented by looping over
  417. // the range [1970, ym), which will spin for any time value with an extremely large year.
  418. auto t = time_from_year(ym) + (day_of_year(static_cast<int>(ym), static_cast<int>(mn) + 1, 1) * ms_per_day);
  419. // 9. Return Day(t) + dt - 1๐”ฝ.
  420. return day(static_cast<double>(t)) + dt - 1;
  421. }
  422. // 21.4.1.16 MakeDate ( day, time ), https://tc39.es/ecma262/#sec-makedate
  423. double make_date(double day, double time)
  424. {
  425. // 1. If day is not finite or time is not finite, return NaN.
  426. if (!isfinite(day) || !isfinite(time))
  427. return NAN;
  428. // 2. Let tv be day ร— msPerDay + time.
  429. auto tv = day * ms_per_day + time;
  430. // 3. If tv is not finite, return NaN.
  431. if (!isfinite(tv))
  432. return NAN;
  433. // 4. Return tv.
  434. return tv;
  435. }
  436. // 21.4.1.17 TimeClip ( time ), https://tc39.es/ecma262/#sec-timeclip
  437. double time_clip(double time)
  438. {
  439. // 1. If time is not finite, return NaN.
  440. if (!isfinite(time))
  441. return NAN;
  442. // 2. If abs(โ„(time)) > 8.64 ร— 10^15, return NaN.
  443. if (fabs(time) > 8.64E15)
  444. return NAN;
  445. // 3. Return ๐”ฝ(! ToIntegerOrInfinity(time)).
  446. return to_integer_or_infinity(time);
  447. }
  448. // 21.4.1.19.1 IsTimeZoneOffsetString ( offsetString ), https://tc39.es/ecma262/#sec-istimezoneoffsetstring
  449. bool is_time_zone_offset_string(StringView offset_string)
  450. {
  451. // 1. Let parseResult be ParseText(StringToCodePoints(offsetString), UTCOffset).
  452. auto parse_result = Temporal::parse_iso8601(Temporal::Production::TimeZoneNumericUTCOffset, offset_string);
  453. // 2. If parseResult is a List of errors, return false.
  454. // 3. Return true.
  455. return parse_result.has_value();
  456. }
  457. // 21.4.1.19.2 ParseTimeZoneOffsetString ( offsetString ), https://tc39.es/ecma262/#sec-parsetimezoneoffsetstring
  458. double parse_time_zone_offset_string(StringView offset_string)
  459. {
  460. // 1. Let parseResult be ParseText(StringToCodePoints(offsetString), UTCOffset).
  461. auto parse_result = Temporal::parse_iso8601(Temporal::Production::TimeZoneNumericUTCOffset, offset_string);
  462. // 2. Assert: parseResult is not a List of errors.
  463. VERIFY(parse_result.has_value());
  464. // 3. Assert: parseResult contains a TemporalSign Parse Node.
  465. VERIFY(parse_result->time_zone_utc_offset_sign.has_value());
  466. // 4. Let parsedSign be the source text matched by the TemporalSign Parse Node contained within parseResult.
  467. auto parsed_sign = *parse_result->time_zone_utc_offset_sign;
  468. i8 sign { 0 };
  469. // 5. If parsedSign is the single code point U+002D (HYPHEN-MINUS) or U+2212 (MINUS SIGN), then
  470. if (parsed_sign.is_one_of("-"sv, "\xE2\x88\x92"sv)) {
  471. // a. Let sign be -1.
  472. sign = -1;
  473. }
  474. // 6. Else,
  475. else {
  476. // a. Let sign be 1.
  477. sign = 1;
  478. }
  479. // 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.
  480. // 8. Assert: parseResult contains an Hour Parse Node.
  481. VERIFY(parse_result->time_zone_utc_offset_hour.has_value());
  482. // 9. Let parsedHours be the source text matched by the Hour Parse Node contained within parseResult.
  483. auto parsed_hours = *parse_result->time_zone_utc_offset_hour;
  484. // 10. Let hours be โ„(StringToNumber(CodePointsToString(parsedHours))).
  485. auto hours = string_to_number(parsed_hours)->as_double();
  486. double minutes { 0 };
  487. double seconds { 0 };
  488. double nanoseconds { 0 };
  489. // 11. If parseResult does not contain a MinuteSecond Parse Node, then
  490. if (!parse_result->time_zone_utc_offset_minute.has_value()) {
  491. // a. Let minutes be 0.
  492. minutes = 0;
  493. }
  494. // 12. Else,
  495. else {
  496. // a. Let parsedMinutes be the source text matched by the first MinuteSecond Parse Node contained within parseResult.
  497. auto parsed_minutes = *parse_result->time_zone_utc_offset_minute;
  498. // b. Let minutes be โ„(StringToNumber(CodePointsToString(parsedMinutes))).
  499. minutes = string_to_number(parsed_minutes)->as_double();
  500. }
  501. // 13. If parseResult does not contain two MinuteSecond Parse Nodes, then
  502. if (!parse_result->time_zone_utc_offset_second.has_value()) {
  503. // a. Let seconds be 0.
  504. seconds = 0;
  505. }
  506. // 14. Else,
  507. else {
  508. // a. Let parsedSeconds be the source text matched by the second secondSecond Parse Node contained within parseResult.
  509. auto parsed_seconds = *parse_result->time_zone_utc_offset_second;
  510. // b. Let seconds be โ„(StringToNumber(CodePointsToString(parsedSeconds))).
  511. seconds = string_to_number(parsed_seconds)->as_double();
  512. }
  513. // 15. If parseResult does not contain a TemporalDecimalFraction Parse Node, then
  514. if (!parse_result->time_zone_utc_offset_fraction.has_value()) {
  515. // a. Let nanoseconds be 0.
  516. nanoseconds = 0;
  517. }
  518. // 16. Else,
  519. else {
  520. // a. Let parsedFraction be the source text matched by the TemporalDecimalFraction Parse Node contained within parseResult.
  521. auto parsed_fraction = *parse_result->time_zone_utc_offset_fraction;
  522. // b. Let fraction be the string-concatenation of CodePointsToString(parsedFraction) and "000000000".
  523. auto fraction = String::formatted("{}000000000", parsed_fraction);
  524. // c. Let nanosecondsString be the substring of fraction from 1 to 10.
  525. auto nanoseconds_string = fraction.substring_view(1, 9);
  526. // d. Let nanoseconds be โ„(StringToNumber(nanosecondsString)).
  527. nanoseconds = string_to_number(nanoseconds_string)->as_double();
  528. }
  529. // 17. Return sign ร— (((hours ร— 60 + minutes) ร— 60 + seconds) ร— 10^9 + nanoseconds).
  530. // NOTE: Using scientific notation (1e9) ensures the result of this expression is a double,
  531. // which is important - otherwise it's all integers and the result overflows!
  532. return sign * (((hours * 60 + minutes) * 60 + seconds) * 1e9 + nanoseconds);
  533. }
  534. }