DateTime.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/CharacterTypes.h>
  7. #include <AK/DateConstants.h>
  8. #include <AK/GenericLexer.h>
  9. #include <AK/String.h>
  10. #include <AK/StringBuilder.h>
  11. #include <AK/Time.h>
  12. #include <LibCore/DateTime.h>
  13. #include <LibUnicode/TimeZone.h>
  14. #include <errno.h>
  15. #include <time.h>
  16. namespace Core {
  17. static Optional<StringView> parse_time_zone_name(GenericLexer& lexer)
  18. {
  19. auto const& time_zones = Unicode::available_time_zones();
  20. auto start_position = lexer.tell();
  21. Optional<StringView> canonicalized_time_zone;
  22. lexer.ignore_until([&](auto) {
  23. auto time_zone = lexer.input().substring_view(start_position, lexer.tell() - start_position + 1);
  24. auto it = time_zones.find_if([&](auto const& candidate) { return time_zone.equals_ignoring_ascii_case(candidate); });
  25. if (it == time_zones.end())
  26. return false;
  27. canonicalized_time_zone = *it;
  28. return true;
  29. });
  30. if (canonicalized_time_zone.has_value())
  31. lexer.ignore();
  32. return canonicalized_time_zone;
  33. }
  34. static void apply_time_zone_offset(StringView time_zone, UnixDateTime& time)
  35. {
  36. if (auto offset = Unicode::time_zone_offset(time_zone, time); offset.has_value())
  37. time -= offset->offset;
  38. }
  39. DateTime DateTime::now()
  40. {
  41. return from_timestamp(time(nullptr));
  42. }
  43. DateTime DateTime::create(int year, int month, int day, int hour, int minute, int second)
  44. {
  45. DateTime dt;
  46. dt.set_time(year, month, day, hour, minute, second);
  47. return dt;
  48. }
  49. DateTime DateTime::from_timestamp(time_t timestamp)
  50. {
  51. struct tm tm;
  52. localtime_r(&timestamp, &tm);
  53. DateTime dt;
  54. dt.m_year = tm.tm_year + 1900;
  55. dt.m_month = tm.tm_mon + 1;
  56. dt.m_day = tm.tm_mday;
  57. dt.m_hour = tm.tm_hour;
  58. dt.m_minute = tm.tm_min;
  59. dt.m_second = tm.tm_sec;
  60. dt.m_timestamp = timestamp;
  61. return dt;
  62. }
  63. unsigned DateTime::weekday() const
  64. {
  65. return ::day_of_week(m_year, m_month, m_day);
  66. }
  67. unsigned DateTime::days_in_month() const
  68. {
  69. return ::days_in_month(m_year, m_month);
  70. }
  71. unsigned DateTime::day_of_year() const
  72. {
  73. return ::day_of_year(m_year, m_month, m_day);
  74. }
  75. bool DateTime::is_leap_year() const
  76. {
  77. return ::is_leap_year(m_year);
  78. }
  79. void DateTime::set_time(int year, int month, int day, int hour, int minute, int second)
  80. {
  81. struct tm tm = {};
  82. tm.tm_sec = second;
  83. tm.tm_min = minute;
  84. tm.tm_hour = hour;
  85. tm.tm_mday = day;
  86. tm.tm_mon = month - 1;
  87. tm.tm_year = year - 1900;
  88. tm.tm_isdst = -1;
  89. // mktime() doesn't read tm.tm_wday and tm.tm_yday, no need to fill them in.
  90. m_timestamp = mktime(&tm);
  91. // mktime() normalizes the components to the right ranges (Jan 32 -> Feb 1 etc), so read fields back out from tm.
  92. m_year = tm.tm_year + 1900;
  93. m_month = tm.tm_mon + 1;
  94. m_day = tm.tm_mday;
  95. m_hour = tm.tm_hour;
  96. m_minute = tm.tm_min;
  97. m_second = tm.tm_sec;
  98. }
  99. void DateTime::set_time_only(int hour, int minute, Optional<int> second)
  100. {
  101. set_time(year(), month(), day(), hour, minute, second.has_value() ? second.release_value() : this->second());
  102. }
  103. void DateTime::set_date(Core::DateTime const& other)
  104. {
  105. set_time(other.year(), other.month(), other.day(), hour(), minute(), second());
  106. }
  107. ErrorOr<String> DateTime::to_string(StringView format, LocalTime local_time) const
  108. {
  109. struct tm tm;
  110. if (local_time == LocalTime::Yes)
  111. localtime_r(&m_timestamp, &tm);
  112. else
  113. gmtime_r(&m_timestamp, &tm);
  114. StringBuilder builder;
  115. size_t const format_len = format.length();
  116. auto format_time_zone_offset = [&](bool with_separator) -> ErrorOr<void> {
  117. struct tm gmt_tm;
  118. gmtime_r(&m_timestamp, &gmt_tm);
  119. gmt_tm.tm_isdst = -1;
  120. auto gmt_timestamp = mktime(&gmt_tm);
  121. auto offset_seconds = static_cast<time_t>(difftime(m_timestamp, gmt_timestamp));
  122. StringView offset_sign;
  123. if (offset_seconds >= 0) {
  124. offset_sign = "+"sv;
  125. } else {
  126. offset_sign = "-"sv;
  127. offset_seconds *= -1;
  128. }
  129. auto offset_hours = offset_seconds / 3600;
  130. auto offset_minutes = (offset_seconds % 3600) / 60;
  131. auto separator = with_separator ? ":"sv : ""sv;
  132. TRY(builder.try_appendff("{}{:02}{}{:02}", offset_sign, offset_hours, separator, offset_minutes));
  133. return {};
  134. };
  135. for (size_t i = 0; i < format_len; ++i) {
  136. if (format[i] != '%') {
  137. TRY(builder.try_append(format[i]));
  138. } else {
  139. if (++i == format_len)
  140. return String {};
  141. switch (format[i]) {
  142. case 'a':
  143. TRY(builder.try_append(short_day_names[tm.tm_wday]));
  144. break;
  145. case 'A':
  146. TRY(builder.try_append(long_day_names[tm.tm_wday]));
  147. break;
  148. case 'b':
  149. TRY(builder.try_append(short_month_names[tm.tm_mon]));
  150. break;
  151. case 'B':
  152. TRY(builder.try_append(long_month_names[tm.tm_mon]));
  153. break;
  154. case 'C':
  155. TRY(builder.try_appendff("{:02}", (tm.tm_year + 1900) / 100));
  156. break;
  157. case 'd':
  158. TRY(builder.try_appendff("{:02}", tm.tm_mday));
  159. break;
  160. case 'D':
  161. TRY(builder.try_appendff("{:02}/{:02}/{:02}", tm.tm_mon + 1, tm.tm_mday, (tm.tm_year + 1900) % 100));
  162. break;
  163. case 'e':
  164. TRY(builder.try_appendff("{:2}", tm.tm_mday));
  165. break;
  166. case 'h':
  167. TRY(builder.try_append(short_month_names[tm.tm_mon]));
  168. break;
  169. case 'H':
  170. TRY(builder.try_appendff("{:02}", tm.tm_hour));
  171. break;
  172. case 'I': {
  173. int display_hour = tm.tm_hour % 12;
  174. if (display_hour == 0)
  175. display_hour = 12;
  176. TRY(builder.try_appendff("{:02}", display_hour));
  177. break;
  178. }
  179. case 'j':
  180. TRY(builder.try_appendff("{:03}", tm.tm_yday + 1));
  181. break;
  182. case 'l': {
  183. int display_hour = tm.tm_hour % 12;
  184. if (display_hour == 0)
  185. display_hour = 12;
  186. TRY(builder.try_appendff("{:2}", display_hour));
  187. break;
  188. }
  189. case 'm':
  190. TRY(builder.try_appendff("{:02}", tm.tm_mon + 1));
  191. break;
  192. case 'M':
  193. TRY(builder.try_appendff("{:02}", tm.tm_min));
  194. break;
  195. case 'n':
  196. TRY(builder.try_append('\n'));
  197. break;
  198. case 'p':
  199. TRY(builder.try_append(tm.tm_hour < 12 ? "AM"sv : "PM"sv));
  200. break;
  201. case 'r': {
  202. int display_hour = tm.tm_hour % 12;
  203. if (display_hour == 0)
  204. display_hour = 12;
  205. TRY(builder.try_appendff("{:02}:{:02}:{:02} {}", display_hour, tm.tm_min, tm.tm_sec, tm.tm_hour < 12 ? "AM" : "PM"));
  206. break;
  207. }
  208. case 'R':
  209. TRY(builder.try_appendff("{:02}:{:02}", tm.tm_hour, tm.tm_min));
  210. break;
  211. case 'S':
  212. TRY(builder.try_appendff("{:02}", tm.tm_sec));
  213. break;
  214. case 't':
  215. TRY(builder.try_append('\t'));
  216. break;
  217. case 'T':
  218. TRY(builder.try_appendff("{:02}:{:02}:{:02}", tm.tm_hour, tm.tm_min, tm.tm_sec));
  219. break;
  220. case 'u':
  221. TRY(builder.try_appendff("{}", tm.tm_wday ? tm.tm_wday : 7));
  222. break;
  223. case 'U': {
  224. int const wday_of_year_beginning = (tm.tm_wday + 6 * tm.tm_yday) % 7;
  225. int const week_number = (tm.tm_yday + wday_of_year_beginning) / 7;
  226. TRY(builder.try_appendff("{:02}", week_number));
  227. break;
  228. }
  229. case 'V': {
  230. int const wday_of_year_beginning = (tm.tm_wday + 6 + 6 * tm.tm_yday) % 7;
  231. int week_number = (tm.tm_yday + wday_of_year_beginning) / 7 + 1;
  232. if (wday_of_year_beginning > 3) {
  233. if (tm.tm_yday >= 7 - wday_of_year_beginning)
  234. --week_number;
  235. else {
  236. int const days_of_last_year = days_in_year(tm.tm_year + 1900 - 1);
  237. int const wday_of_last_year_beginning = (wday_of_year_beginning + 6 * days_of_last_year) % 7;
  238. week_number = (days_of_last_year + wday_of_last_year_beginning) / 7 + 1;
  239. if (wday_of_last_year_beginning > 3)
  240. --week_number;
  241. }
  242. }
  243. TRY(builder.try_appendff("{:02}", week_number));
  244. break;
  245. }
  246. case 'w':
  247. TRY(builder.try_appendff("{}", tm.tm_wday));
  248. break;
  249. case 'W': {
  250. int const wday_of_year_beginning = (tm.tm_wday + 6 + 6 * tm.tm_yday) % 7;
  251. int const week_number = (tm.tm_yday + wday_of_year_beginning) / 7;
  252. TRY(builder.try_appendff("{:02}", week_number));
  253. break;
  254. }
  255. case 'y':
  256. TRY(builder.try_appendff("{:02}", (tm.tm_year + 1900) % 100));
  257. break;
  258. case 'Y':
  259. TRY(builder.try_appendff("{}", tm.tm_year + 1900));
  260. break;
  261. case 'z':
  262. TRY(format_time_zone_offset(false));
  263. break;
  264. case ':':
  265. if (++i == format_len) {
  266. TRY(builder.try_append("%:"sv));
  267. break;
  268. }
  269. if (format[i] != 'z') {
  270. TRY(builder.try_append("%:"sv));
  271. TRY(builder.try_append(format[i]));
  272. break;
  273. }
  274. TRY(format_time_zone_offset(true));
  275. break;
  276. case 'Z': {
  277. auto const* timezone_name = tzname[tm.tm_isdst == 0 ? 0 : 1];
  278. TRY(builder.try_append({ timezone_name, strlen(timezone_name) }));
  279. break;
  280. }
  281. case '%':
  282. TRY(builder.try_append('%'));
  283. break;
  284. default:
  285. TRY(builder.try_append('%'));
  286. TRY(builder.try_append(format[i]));
  287. break;
  288. }
  289. }
  290. }
  291. return builder.to_string();
  292. }
  293. ByteString DateTime::to_byte_string(StringView format, LocalTime local_time) const
  294. {
  295. return MUST(to_string(format, local_time)).to_byte_string();
  296. }
  297. Optional<DateTime> DateTime::parse(StringView format, StringView string)
  298. {
  299. unsigned format_pos = 0;
  300. struct tm tm = {};
  301. tm.tm_isdst = -1;
  302. auto parsing_failed = false;
  303. auto tm_represents_utc_time = false;
  304. Optional<StringView> parsed_time_zone;
  305. GenericLexer string_lexer(string);
  306. auto parse_number = [&] {
  307. auto result = string_lexer.consume_decimal_integer<int>();
  308. if (result.is_error()) {
  309. parsing_failed = true;
  310. return 0;
  311. }
  312. return result.value();
  313. };
  314. auto consume = [&](char c) {
  315. if (!string_lexer.consume_specific(c))
  316. parsing_failed = true;
  317. };
  318. auto consume_specific_ascii_case_insensitive = [&](StringView name) {
  319. auto next_string = string_lexer.peek_string(name.length());
  320. if (next_string.has_value() && next_string->equals_ignoring_ascii_case(name)) {
  321. string_lexer.consume(name.length());
  322. return true;
  323. }
  324. return false;
  325. };
  326. while (format_pos < format.length() && !string_lexer.is_eof()) {
  327. if (format[format_pos] != '%') {
  328. consume(format[format_pos]);
  329. format_pos++;
  330. continue;
  331. }
  332. format_pos++;
  333. if (format_pos == format.length())
  334. return {};
  335. switch (format[format_pos]) {
  336. case 'a': {
  337. auto wday = 0;
  338. for (auto name : short_day_names) {
  339. if (consume_specific_ascii_case_insensitive(name)) {
  340. tm.tm_wday = wday;
  341. break;
  342. }
  343. ++wday;
  344. }
  345. if (wday == 7)
  346. return {};
  347. break;
  348. }
  349. case 'A': {
  350. auto wday = 0;
  351. for (auto name : long_day_names) {
  352. if (consume_specific_ascii_case_insensitive(name)) {
  353. tm.tm_wday = wday;
  354. break;
  355. }
  356. ++wday;
  357. }
  358. if (wday == 7)
  359. return {};
  360. break;
  361. }
  362. case 'h':
  363. case 'b': {
  364. auto mon = 0;
  365. for (auto name : short_month_names) {
  366. if (consume_specific_ascii_case_insensitive(name)) {
  367. tm.tm_mon = mon;
  368. break;
  369. }
  370. ++mon;
  371. }
  372. if (mon == 12)
  373. return {};
  374. break;
  375. }
  376. case 'B': {
  377. auto mon = 0;
  378. for (auto name : long_month_names) {
  379. if (consume_specific_ascii_case_insensitive(name)) {
  380. tm.tm_mon = mon;
  381. break;
  382. }
  383. ++mon;
  384. }
  385. if (mon == 12)
  386. return {};
  387. break;
  388. }
  389. case 'C': {
  390. int num = parse_number();
  391. tm.tm_year = (num - 19) * 100;
  392. break;
  393. }
  394. case 'd':
  395. tm.tm_mday = parse_number();
  396. break;
  397. case 'D': {
  398. int mon = parse_number();
  399. consume('/');
  400. int day = parse_number();
  401. consume('/');
  402. int year = parse_number();
  403. tm.tm_mon = mon + 1;
  404. tm.tm_mday = day;
  405. tm.tm_year = (year + 1900) % 100;
  406. break;
  407. }
  408. case 'e':
  409. tm.tm_mday = parse_number();
  410. break;
  411. case 'H':
  412. tm.tm_hour = parse_number();
  413. break;
  414. case 'I': {
  415. int num = parse_number();
  416. tm.tm_hour = num % 12;
  417. break;
  418. }
  419. case 'j':
  420. // a little trickery here... we can get mktime() to figure out mon and mday using out of range values.
  421. // yday is not used so setting it is pointless.
  422. tm.tm_mday = parse_number();
  423. tm.tm_mon = 0;
  424. mktime(&tm);
  425. break;
  426. case 'm': {
  427. int num = parse_number();
  428. tm.tm_mon = num - 1;
  429. break;
  430. }
  431. case 'M':
  432. tm.tm_min = parse_number();
  433. break;
  434. case 'n':
  435. case 't':
  436. string_lexer.consume_while(is_ascii_blank);
  437. break;
  438. case 'r':
  439. case 'p': {
  440. auto ampm = string_lexer.consume(2);
  441. if (ampm == "PM") {
  442. if (tm.tm_hour < 12)
  443. tm.tm_hour += 12;
  444. } else if (ampm != "AM") {
  445. return {};
  446. }
  447. break;
  448. }
  449. case 'R':
  450. tm.tm_hour = parse_number();
  451. consume(':');
  452. tm.tm_min = parse_number();
  453. break;
  454. case 'S':
  455. tm.tm_sec = parse_number();
  456. break;
  457. case 'T':
  458. tm.tm_hour = parse_number();
  459. consume(':');
  460. tm.tm_min = parse_number();
  461. consume(':');
  462. tm.tm_sec = parse_number();
  463. break;
  464. case 'w':
  465. tm.tm_wday = parse_number();
  466. break;
  467. case 'y': {
  468. int year = parse_number();
  469. tm.tm_year = year <= 99 && year > 69 ? 1900 + year : 2000 + year;
  470. break;
  471. }
  472. case 'Y': {
  473. int year = parse_number();
  474. tm.tm_year = year - 1900;
  475. break;
  476. }
  477. case 'z': {
  478. tm_represents_utc_time = true;
  479. if (string_lexer.consume_specific('Z')) {
  480. // UTC time
  481. break;
  482. }
  483. int sign;
  484. if (string_lexer.consume_specific('+'))
  485. sign = -1;
  486. else if (string_lexer.consume_specific('-'))
  487. sign = +1;
  488. else
  489. return {};
  490. auto hours = parse_number();
  491. int minutes;
  492. if (string_lexer.consume_specific(':')) {
  493. minutes = parse_number();
  494. } else {
  495. minutes = hours % 100;
  496. hours = hours / 100;
  497. }
  498. tm.tm_hour += sign * hours;
  499. tm.tm_min += sign * minutes;
  500. break;
  501. }
  502. case 'x': {
  503. tm_represents_utc_time = true;
  504. auto hours = parse_number();
  505. int minutes;
  506. if (string_lexer.consume_specific(':')) {
  507. minutes = parse_number();
  508. } else {
  509. minutes = hours % 100;
  510. hours = hours / 100;
  511. }
  512. tm.tm_hour -= hours;
  513. tm.tm_min -= minutes;
  514. break;
  515. }
  516. case 'X': {
  517. if (!string_lexer.consume_specific('.'))
  518. return {};
  519. auto discarded = parse_number();
  520. (void)discarded; // NOTE: the tm structure does not support sub second precision, so drop this value.
  521. break;
  522. }
  523. case 'Z':
  524. parsed_time_zone = parse_time_zone_name(string_lexer);
  525. if (!parsed_time_zone.has_value())
  526. return {};
  527. tm_represents_utc_time = true;
  528. break;
  529. case '+': {
  530. Optional<char> next_format_character;
  531. if (format_pos + 1 < format.length()) {
  532. next_format_character = format[format_pos + 1];
  533. // Disallow another formatter directly after %+. This is to avoid ambiguity when parsing a string like
  534. // "ignoreJan" with "%+%b", as it would be non-trivial to know that where the %b field begins.
  535. if (next_format_character == '%')
  536. return {};
  537. }
  538. auto discarded = string_lexer.consume_until([&](auto ch) { return ch == next_format_character; });
  539. if (discarded.is_empty())
  540. return {};
  541. break;
  542. }
  543. case '%':
  544. consume('%');
  545. break;
  546. default:
  547. parsing_failed = true;
  548. break;
  549. }
  550. if (parsing_failed)
  551. return {};
  552. format_pos++;
  553. }
  554. if (!string_lexer.is_eof() || format_pos != format.length())
  555. return {};
  556. // If an explicit time zone offset was present, the time in tm was shifted to UTC. If a time zone name was present,
  557. // the time in tm needs to be shifted to UTC. In both cases, convert the result to local time, as that is what is
  558. // expected by `mktime`.
  559. if (tm_represents_utc_time) {
  560. auto utc_time = UnixDateTime::from_seconds_since_epoch(timegm(&tm));
  561. if (parsed_time_zone.has_value())
  562. apply_time_zone_offset(*parsed_time_zone, utc_time);
  563. time_t utc_time_t = utc_time.seconds_since_epoch();
  564. localtime_r(&utc_time_t, &tm);
  565. }
  566. return DateTime::from_timestamp(mktime(&tm));
  567. }
  568. }