DateTime.cpp 19 KB

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