Date.cpp 31 KB

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