DateTime.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 <LibIPC/Forward.h>
  9. #include <time.h>
  10. namespace Core {
  11. // Represents a time in local time.
  12. class DateTime {
  13. public:
  14. time_t timestamp() const { return m_timestamp; }
  15. unsigned year() const { return m_year; }
  16. unsigned month() const { return m_month; }
  17. unsigned day() const { return m_day; }
  18. unsigned hour() const { return m_hour; }
  19. unsigned minute() const { return m_minute; }
  20. unsigned second() const { return m_second; }
  21. unsigned weekday() const;
  22. unsigned days_in_month() const;
  23. unsigned day_of_year() const;
  24. bool is_leap_year() const;
  25. void set_time(int year, int month = 1, int day = 0, int hour = 0, int minute = 0, int second = 0);
  26. String to_string(const String& format = "%Y-%m-%d %H:%M:%S") const;
  27. static DateTime create(int year, int month = 1, int day = 0, int hour = 0, int minute = 0, int second = 0);
  28. static DateTime now();
  29. static DateTime from_timestamp(time_t);
  30. static Optional<DateTime> parse(const String& format, const String& string);
  31. bool operator<(const DateTime& other) const { return m_timestamp < other.m_timestamp; }
  32. private:
  33. time_t m_timestamp { 0 };
  34. int m_year { 0 };
  35. int m_month { 0 };
  36. int m_day { 0 };
  37. int m_hour { 0 };
  38. int m_minute { 0 };
  39. int m_second { 0 };
  40. };
  41. }
  42. namespace IPC {
  43. bool encode(IPC::Encoder&, const Core::DateTime&);
  44. bool decode(IPC::Decoder&, Core::DateTime&);
  45. }