DateTime.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/DeprecatedString.h>
  8. #include <AK/StringView.h>
  9. #include <LibIPC/Forward.h>
  10. #include <time.h>
  11. namespace Core {
  12. // Represents a time in local time.
  13. class DateTime {
  14. public:
  15. time_t timestamp() const { return m_timestamp; }
  16. unsigned year() const { return m_year; }
  17. unsigned month() const { return m_month; }
  18. unsigned day() const { return m_day; }
  19. unsigned hour() const { return m_hour; }
  20. unsigned minute() const { return m_minute; }
  21. unsigned second() const { return m_second; }
  22. unsigned weekday() const;
  23. unsigned days_in_month() const;
  24. unsigned day_of_year() const;
  25. bool is_leap_year() const;
  26. void set_time(int year, int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0);
  27. ErrorOr<String> to_string(StringView format = "%Y-%m-%d %H:%M:%S"sv) const;
  28. DeprecatedString to_deprecated_string(StringView format = "%Y-%m-%d %H:%M:%S"sv) const;
  29. static DateTime create(int year, int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0);
  30. static DateTime now();
  31. static DateTime from_timestamp(time_t);
  32. static Optional<DateTime> parse(StringView format, DeprecatedString const& string);
  33. bool operator<(DateTime const& other) const { return m_timestamp < other.m_timestamp; }
  34. bool operator==(DateTime const& other) const { return m_timestamp == other.m_timestamp; }
  35. private:
  36. time_t m_timestamp { 0 };
  37. int m_year { 0 };
  38. int m_month { 0 };
  39. int m_day { 0 };
  40. int m_hour { 0 };
  41. int m_minute { 0 };
  42. int m_second { 0 };
  43. };
  44. }
  45. namespace AK {
  46. template<>
  47. struct Formatter<Core::DateTime> : StandardFormatter {
  48. ErrorOr<void> format(FormatBuilder& builder, Core::DateTime const& value)
  49. {
  50. // Can't use DateTime::to_string() here: It doesn't propagate allocation failure.
  51. return builder.builder().try_appendff("{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}"sv,
  52. value.year(), value.month(), value.day(),
  53. value.hour(), value.minute(), value.second());
  54. }
  55. };
  56. }
  57. namespace IPC {
  58. template<>
  59. ErrorOr<void> encode(Encoder&, Core::DateTime const&);
  60. template<>
  61. ErrorOr<Core::DateTime> decode(Decoder&);
  62. }