DateTime.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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/String.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. String to_string(StringView format = "%Y-%m-%d %H:%M:%S"sv) const;
  28. static DateTime create(int year, int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0);
  29. static DateTime now();
  30. static DateTime from_timestamp(time_t);
  31. static Optional<DateTime> parse(StringView format, String const& string);
  32. bool operator<(DateTime const& other) const { return m_timestamp < other.m_timestamp; }
  33. private:
  34. time_t m_timestamp { 0 };
  35. int m_year { 0 };
  36. int m_month { 0 };
  37. int m_day { 0 };
  38. int m_hour { 0 };
  39. int m_minute { 0 };
  40. int m_second { 0 };
  41. };
  42. }
  43. namespace IPC {
  44. bool encode(Encoder&, Core::DateTime const&);
  45. ErrorOr<void> decode(Decoder&, Core::DateTime&);
  46. }