Date.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /*
  2. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2022, Tim Flynn <trflynn89@pm.me>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/StringBuilder.h>
  8. #include <AK/Time.h>
  9. #include <LibCore/DateTime.h>
  10. #include <LibJS/Runtime/AbstractOperations.h>
  11. #include <LibJS/Runtime/Date.h>
  12. #include <LibJS/Runtime/GlobalObject.h>
  13. #include <LibTimeZone/TimeZone.h>
  14. #include <time.h>
  15. namespace JS {
  16. Date* Date::create(GlobalObject& global_object, Core::DateTime datetime, i16 milliseconds, bool is_invalid)
  17. {
  18. return global_object.heap().allocate<Date>(global_object, datetime, milliseconds, is_invalid, *global_object.date_prototype());
  19. }
  20. Date* Date::create(GlobalObject& global_object, double date_value)
  21. {
  22. return global_object.heap().allocate<Date>(global_object, date_value, *global_object.date_prototype());
  23. }
  24. Date::Date(Core::DateTime datetime, i16 milliseconds, bool is_invalid, Object& prototype)
  25. : Object(prototype)
  26. , m_datetime(datetime)
  27. , m_milliseconds(milliseconds)
  28. , m_is_invalid(is_invalid)
  29. {
  30. }
  31. Date::Date(double date_value, Object& prototype)
  32. : Object(prototype)
  33. , m_date_value(date_value)
  34. {
  35. }
  36. Date::~Date()
  37. {
  38. }
  39. tm Date::to_utc_tm() const
  40. {
  41. time_t timestamp = m_datetime.timestamp();
  42. struct tm tm;
  43. gmtime_r(&timestamp, &tm);
  44. return tm;
  45. }
  46. int Date::utc_date() const
  47. {
  48. return to_utc_tm().tm_mday;
  49. }
  50. int Date::utc_day() const
  51. {
  52. return to_utc_tm().tm_wday;
  53. }
  54. int Date::utc_full_year() const
  55. {
  56. return to_utc_tm().tm_year + 1900;
  57. }
  58. int Date::utc_hours() const
  59. {
  60. return to_utc_tm().tm_hour;
  61. }
  62. int Date::utc_minutes() const
  63. {
  64. return to_utc_tm().tm_min;
  65. }
  66. int Date::utc_month() const
  67. {
  68. return to_utc_tm().tm_mon;
  69. }
  70. int Date::utc_seconds() const
  71. {
  72. return to_utc_tm().tm_sec;
  73. }
  74. String Date::gmt_date_string() const
  75. {
  76. // Mon, 18 Dec 1995 17:28:35 GMT
  77. // FIXME: Note that we're totally cheating with the timezone part here..
  78. return datetime().to_string("%a, %e %b %Y %T GMT");
  79. }
  80. String Date::iso_date_string() const
  81. {
  82. int year = year_from_time(m_date_value);
  83. StringBuilder builder;
  84. if (year < 0)
  85. builder.appendff("-{:06}", -year);
  86. else if (year > 9999)
  87. builder.appendff("+{:06}", year);
  88. else
  89. builder.appendff("{:04}", year);
  90. builder.append('-');
  91. builder.appendff("{:02}", month_from_time(m_date_value) + 1);
  92. builder.append('-');
  93. builder.appendff("{:02}", date_from_time(m_date_value));
  94. builder.append('T');
  95. builder.appendff("{:02}", hour_from_time(m_date_value));
  96. builder.append(':');
  97. builder.appendff("{:02}", min_from_time(m_date_value));
  98. builder.append(':');
  99. builder.appendff("{:02}", sec_from_time(m_date_value));
  100. builder.append('.');
  101. builder.appendff("{:03}", ms_from_time(m_date_value));
  102. builder.append('Z');
  103. return builder.build();
  104. }
  105. // https://tc39.es/ecma262/#eqn-HoursPerDay
  106. static constexpr double HOURS_PER_DAY = 24;
  107. // https://tc39.es/ecma262/#eqn-MinutesPerHour
  108. static constexpr double MINUTES_PER_HOUR = 60;
  109. // https://tc39.es/ecma262/#eqn-SecondsPerMinute
  110. static constexpr double SECONDS_PER_MINUTE = 60;
  111. // https://tc39.es/ecma262/#eqn-msPerSecond
  112. static constexpr double MS_PER_SECOND = 1000;
  113. // https://tc39.es/ecma262/#eqn-msPerMinute
  114. static constexpr double MS_PER_MINUTE = 60000;
  115. // https://tc39.es/ecma262/#eqn-msPerHour
  116. static constexpr double MS_PER_HOUR = 3600000;
  117. // https://tc39.es/ecma262/#eqn-msPerDay
  118. static constexpr double MS_PER_DAY = 86400000;
  119. // DayWithinYear(t), https://tc39.es/ecma262/#eqn-DayWithinYear
  120. u16 day_within_year(double t)
  121. {
  122. // Day(t) - DayFromYear(YearFromTime(t))
  123. return static_cast<u16>(day(t) - day_from_year(year_from_time(t)));
  124. }
  125. // DateFromTime(t), https://tc39.es/ecma262/#sec-date-number
  126. u8 date_from_time(double t)
  127. {
  128. switch (month_from_time(t)) {
  129. // DayWithinYear(t) + 1𝔽 if MonthFromTime(t) = +0𝔽
  130. case 0:
  131. return day_within_year(t) + 1;
  132. // DayWithinYear(t) - 30𝔽 if MonthFromTime(t) = 1𝔽
  133. case 1:
  134. return day_within_year(t) - 30;
  135. // DayWithinYear(t) - 58𝔽 - InLeapYear(t) if MonthFromTime(t) = 2𝔽
  136. case 2:
  137. return day_within_year(t) - 58 - in_leap_year(t);
  138. // DayWithinYear(t) - 89𝔽 - InLeapYear(t) if MonthFromTime(t) = 3𝔽
  139. case 3:
  140. return day_within_year(t) - 89 - in_leap_year(t);
  141. // DayWithinYear(t) - 119𝔽 - InLeapYear(t) if MonthFromTime(t) = 4𝔽
  142. case 4:
  143. return day_within_year(t) - 119 - in_leap_year(t);
  144. // DayWithinYear(t) - 150𝔽 - InLeapYear(t) if MonthFromTime(t) = 5𝔽
  145. case 5:
  146. return day_within_year(t) - 150 - in_leap_year(t);
  147. // DayWithinYear(t) - 180𝔽 - InLeapYear(t) if MonthFromTime(t) = 6𝔽
  148. case 6:
  149. return day_within_year(t) - 180 - in_leap_year(t);
  150. // DayWithinYear(t) - 211𝔽 - InLeapYear(t) if MonthFromTime(t) = 7𝔽
  151. case 7:
  152. return day_within_year(t) - 211 - in_leap_year(t);
  153. // DayWithinYear(t) - 242𝔽 - InLeapYear(t) if MonthFromTime(t) = 8𝔽
  154. case 8:
  155. return day_within_year(t) - 242 - in_leap_year(t);
  156. // DayWithinYear(t) - 272𝔽 - InLeapYear(t) if MonthFromTime(t) = 9𝔽
  157. case 9:
  158. return day_within_year(t) - 272 - in_leap_year(t);
  159. // DayWithinYear(t) - 303𝔽 - InLeapYear(t) if MonthFromTime(t) = 10𝔽
  160. case 10:
  161. return day_within_year(t) - 303 - in_leap_year(t);
  162. // DayWithinYear(t) - 333𝔽 - InLeapYear(t) if MonthFromTime(t) = 11𝔽
  163. case 11:
  164. return day_within_year(t) - 333 - in_leap_year(t);
  165. default:
  166. VERIFY_NOT_REACHED();
  167. }
  168. }
  169. // DaysInYear(y), https://tc39.es/ecma262/#eqn-DaysInYear
  170. u16 days_in_year(i32 y)
  171. {
  172. // 365𝔽 if (ℝ(y) modulo 4) ≠ 0
  173. if (y % 4 != 0)
  174. return 365;
  175. // 366𝔽 if (ℝ(y) modulo 4) = 0 and (ℝ(y) modulo 100) ≠ 0
  176. if (y % 4 == 0 && y % 100 != 0)
  177. return 366;
  178. // 365𝔽 if (ℝ(y) modulo 100) = 0 and (ℝ(y) modulo 400) ≠ 0
  179. if (y % 100 == 0 && y % 400 != 0)
  180. return 365;
  181. // 366𝔽 if (ℝ(y) modulo 400) = 0
  182. if (y % 400 == 0)
  183. return 366;
  184. VERIFY_NOT_REACHED();
  185. }
  186. // DayFromYear(y), https://tc39.es/ecma262/#eqn-DaysFromYear
  187. double day_from_year(i32 y)
  188. {
  189. // 𝔽(365 × (ℝ(y) - 1970) + floor((ℝ(y) - 1969) / 4) - floor((ℝ(y) - 1901) / 100) + floor((ℝ(y) - 1601) / 400))
  190. return 365 * (y - 1970) + floor((y - 1969) / 4.0) - floor((y - 1901) / 100.0) + floor((y - 1601) / 400.0);
  191. }
  192. // TimeFromYear(y), https://tc39.es/ecma262/#eqn-TimeFromYear
  193. double time_from_year(i32 y)
  194. {
  195. // msPerDay × DayFromYear(y)
  196. return MS_PER_DAY * day_from_year(y);
  197. }
  198. // YearFromTime(t), https://tc39.es/ecma262/#eqn-YearFromTime
  199. i32 year_from_time(double t)
  200. {
  201. // the largest integral Number y (closest to +∞) such that TimeFromYear(y) ≤ t
  202. // Approximation using average number of milliseconds per year. We might have to adjust this guess afterwards.
  203. auto year = static_cast<i32>(t / (365.2425 * MS_PER_DAY) + 1970);
  204. auto year_t = time_from_year(year);
  205. if (year_t > t)
  206. year--;
  207. else if (year_t + days_in_year(year) * MS_PER_DAY <= t)
  208. year++;
  209. return year;
  210. }
  211. // InLeapYear(t), https://tc39.es/ecma262/#eqn-InLeapYear
  212. bool in_leap_year(double t)
  213. {
  214. // +0𝔽 if DaysInYear(YearFromTime(t)) = 365𝔽
  215. // 1𝔽 if DaysInYear(YearFromTime(t)) = 366𝔽
  216. return days_in_year(year_from_time(t)) == 366;
  217. }
  218. // MonthFromTime(t), https://tc39.es/ecma262/#eqn-MonthFromTime
  219. u8 month_from_time(double t)
  220. {
  221. auto in_leap_year = JS::in_leap_year(t);
  222. auto day_within_year = JS::day_within_year(t);
  223. // +0𝔽 if +0𝔽 ≤ DayWithinYear(t) < 31𝔽
  224. if (day_within_year < 31)
  225. return 0;
  226. // 1𝔽 if 31𝔽 ≤ DayWithinYear(t) < 59𝔽 + InLeapYear(t)
  227. if (31 <= day_within_year && day_within_year < 59 + in_leap_year)
  228. return 1;
  229. // 2𝔽 if 59𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 90𝔽 + InLeapYear(t)
  230. if (59 + in_leap_year <= day_within_year && day_within_year < 90 + in_leap_year)
  231. return 2;
  232. // 3𝔽 if 90𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 120𝔽 + InLeapYear(t)
  233. if (90 + in_leap_year <= day_within_year && day_within_year < 120 + in_leap_year)
  234. return 3;
  235. // 4𝔽 if 120𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 151𝔽 + InLeapYear(t)
  236. if (120 + in_leap_year <= day_within_year && day_within_year < 151 + in_leap_year)
  237. return 4;
  238. // 5𝔽 if 151𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 181𝔽 + InLeapYear(t)
  239. if (151 + in_leap_year <= day_within_year && day_within_year < 181 + in_leap_year)
  240. return 5;
  241. // 6𝔽 if 181𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 212𝔽 + InLeapYear(t)
  242. if (181 + in_leap_year <= day_within_year && day_within_year < 212 + in_leap_year)
  243. return 6;
  244. // 7𝔽 if 212𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 243𝔽 + InLeapYear(t)
  245. if (212 + in_leap_year <= day_within_year && day_within_year < 243 + in_leap_year)
  246. return 7;
  247. // 8𝔽 if 243𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 273𝔽 + InLeapYear(t)
  248. if (243 + in_leap_year <= day_within_year && day_within_year < 273 + in_leap_year)
  249. return 8;
  250. // 9𝔽 if 273𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 304𝔽 + InLeapYear(t)
  251. if (273 + in_leap_year <= day_within_year && day_within_year < 304 + in_leap_year)
  252. return 9;
  253. // 10𝔽 if 304𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 334𝔽 + InLeapYear(t)
  254. if (304 + in_leap_year <= day_within_year && day_within_year < 334 + in_leap_year)
  255. return 10;
  256. // 11𝔽 if 334𝔽 + InLeapYear(t) ≤ DayWithinYear(t) < 365𝔽 + InLeapYear(t)
  257. if (334 + in_leap_year <= day_within_year && day_within_year < 365 + in_leap_year)
  258. return 11;
  259. VERIFY_NOT_REACHED();
  260. }
  261. // HourFromTime(t), https://tc39.es/ecma262/#eqn-HourFromTime
  262. u8 hour_from_time(double t)
  263. {
  264. // 𝔽(floor(ℝ(t / msPerHour)) modulo HoursPerDay)
  265. return static_cast<u8>(modulo(floor(t / MS_PER_HOUR), HOURS_PER_DAY));
  266. }
  267. // MinFromTime(t), https://tc39.es/ecma262/#eqn-MinFromTime
  268. u8 min_from_time(double t)
  269. {
  270. // 𝔽(floor(ℝ(t / msPerMinute)) modulo MinutesPerHour)
  271. return static_cast<u8>(modulo(floor(t / MS_PER_MINUTE), MINUTES_PER_HOUR));
  272. }
  273. // SecFromTime(t), https://tc39.es/ecma262/#eqn-SecFromTime
  274. u8 sec_from_time(double t)
  275. {
  276. // 𝔽(floor(ℝ(t / msPerSecond)) modulo SecondsPerMinute)
  277. return static_cast<u8>(modulo(floor(t / MS_PER_SECOND), SECONDS_PER_MINUTE));
  278. }
  279. // msFromTime(t), https://tc39.es/ecma262/#eqn-msFromTime
  280. u16 ms_from_time(double t)
  281. {
  282. // 𝔽(ℝ(t) modulo msPerSecond)
  283. return static_cast<u16>(modulo(t, MS_PER_SECOND));
  284. }
  285. // 21.4.1.6 Week Day, https://tc39.es/ecma262/#sec-week-day
  286. u8 week_day(double t)
  287. {
  288. // 𝔽(ℝ(Day(t) + 4𝔽) modulo 7)
  289. return static_cast<u8>(modulo(day(t) + 4, 7));
  290. }
  291. // 21.4.1.7 LocalTZA ( t, isUTC ), https://tc39.es/ecma262/#sec-local-time-zone-adjustment
  292. double local_tza(double time, [[maybe_unused]] bool is_utc, Optional<StringView> time_zone_override)
  293. {
  294. // The time_zone_override parameter is non-standard, but allows callers to override the system
  295. // time zone with a specific value without setting environment variables.
  296. auto time_zone = time_zone_override.value_or(TimeZone::current_time_zone());
  297. // When isUTC is true, LocalTZA( tUTC, true ) should return the offset of the local time zone from
  298. // UTC measured in milliseconds at time represented by time value tUTC. When the result is added to
  299. // tUTC, it should yield the corresponding Number tlocal.
  300. // When isUTC is false, LocalTZA( tlocal, false ) should return the offset of the local time zone from
  301. // UTC measured in milliseconds at local time represented by Number tlocal. When the result is subtracted
  302. // from tlocal, it should yield the corresponding time value tUTC.
  303. auto time_since_epoch = Value(time).is_finite_number() ? AK::Time::from_milliseconds(time) : AK::Time::max();
  304. auto maybe_offset = TimeZone::get_time_zone_offset(time_zone, time_since_epoch);
  305. return maybe_offset.value_or(0) * 1000;
  306. }
  307. // 21.4.1.8 LocalTime ( t ), https://tc39.es/ecma262/#sec-localtime
  308. double local_time(double time)
  309. {
  310. // 1. Return t + LocalTZA(t, true).
  311. return time + local_tza(time, true);
  312. }
  313. // 21.4.1.9 UTC ( t ), https://tc39.es/ecma262/#sec-utc-t
  314. double utc_time(double time)
  315. {
  316. // 1. Return t - LocalTZA(t, false).
  317. return time - local_tza(time, false);
  318. }
  319. // 21.4.1.11 MakeTime ( hour, min, sec, ms ), https://tc39.es/ecma262/#sec-maketime
  320. Value make_time(GlobalObject& global_object, Value hour, Value min, Value sec, Value ms)
  321. {
  322. // 1. If hour is not finite or min is not finite or sec is not finite or ms is not finite, return NaN.
  323. if (!hour.is_finite_number() || !min.is_finite_number() || !sec.is_finite_number() || !ms.is_finite_number())
  324. return js_nan();
  325. // 2. Let h be 𝔽(! ToIntegerOrInfinity(hour)).
  326. auto h = MUST(hour.to_integer_or_infinity(global_object));
  327. // 3. Let m be 𝔽(! ToIntegerOrInfinity(min)).
  328. auto m = MUST(min.to_integer_or_infinity(global_object));
  329. // 4. Let s be 𝔽(! ToIntegerOrInfinity(sec)).
  330. auto s = MUST(sec.to_integer_or_infinity(global_object));
  331. // 5. Let milli be 𝔽(! ToIntegerOrInfinity(ms)).
  332. auto milli = MUST(ms.to_integer_or_infinity(global_object));
  333. // 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 +).
  334. // NOTE: C++ arithmetic abides by IEEE 754 rules
  335. auto t = ((h * MS_PER_HOUR + m * MS_PER_MINUTE) + s * MS_PER_SECOND) + milli;
  336. // 7. Return t.
  337. return Value(t);
  338. }
  339. // Day(t), https://tc39.es/ecma262/#eqn-Day
  340. double day(double time_value)
  341. {
  342. return floor(time_value / MS_PER_DAY);
  343. }
  344. // TimeWithinDay(t), https://tc39.es/ecma262/#eqn-TimeWithinDay
  345. double time_within_day(double time)
  346. {
  347. // 𝔽(ℝ(t) modulo ℝ(msPerDay))
  348. return modulo(time, MS_PER_DAY);
  349. }
  350. // 21.4.1.12 MakeDay ( year, month, date ), https://tc39.es/ecma262/#sec-makeday
  351. Value make_day(GlobalObject& global_object, Value year, Value month, Value date)
  352. {
  353. // 1. If year is not finite or month is not finite or date is not finite, return NaN.
  354. if (!year.is_finite_number() || !month.is_finite_number() || !date.is_finite_number())
  355. return js_nan();
  356. // 2. Let y be 𝔽(! ToIntegerOrInfinity(year)).
  357. auto y = MUST(year.to_integer_or_infinity(global_object));
  358. // 3. Let m be 𝔽(! ToIntegerOrInfinity(month)).
  359. auto m = MUST(month.to_integer_or_infinity(global_object));
  360. // 4. Let dt be 𝔽(! ToIntegerOrInfinity(date)).
  361. auto dt = MUST(date.to_integer_or_infinity(global_object));
  362. // 5. Let ym be y + 𝔽(floor(ℝ(m) / 12)).
  363. auto ym = y + floor(m / 12);
  364. // 6. If ym is not finite, return NaN.
  365. if (!Value(ym).is_finite_number())
  366. return js_nan();
  367. // 7. Let mn be 𝔽(ℝ(m) modulo 12).
  368. auto mn = modulo(m, 12);
  369. // 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.
  370. if (!AK::is_within_range<int>(ym) || !AK::is_within_range<int>(mn + 1))
  371. return js_nan();
  372. auto t = days_since_epoch(static_cast<int>(ym), static_cast<int>(mn) + 1, 1) * MS_PER_DAY;
  373. // 9. Return Day(t) + dt - 1𝔽.
  374. return Value(day(static_cast<double>(t)) + dt - 1);
  375. }
  376. // 21.4.1.13 MakeDate ( day, time ), https://tc39.es/ecma262/#sec-makedate
  377. Value make_date(Value day, Value time)
  378. {
  379. // 1. If day is not finite or time is not finite, return NaN.
  380. if (!day.is_finite_number() || !time.is_finite_number())
  381. return js_nan();
  382. // 2. Let tv be day × msPerDay + time.
  383. auto tv = Value(day.as_double() * MS_PER_DAY + time.as_double());
  384. // 3. If tv is not finite, return NaN.
  385. if (!tv.is_finite_number())
  386. return js_nan();
  387. // 4. Return tv.
  388. return tv;
  389. }
  390. // 21.4.1.14 TimeClip ( time ), https://tc39.es/ecma262/#sec-timeclip
  391. Value time_clip(GlobalObject& global_object, Value time)
  392. {
  393. // 1. If time is not finite, return NaN.
  394. if (!time.is_finite_number())
  395. return js_nan();
  396. // 2. If abs(ℝ(time)) > 8.64 × 10^15, return NaN.
  397. if (fabs(time.as_double()) > 8.64E15)
  398. return js_nan();
  399. // 3. Return 𝔽(! ToIntegerOrInfinity(time)).
  400. return Value(MUST(time.to_integer_or_infinity(global_object)));
  401. }
  402. }