Date.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. /*
  2. * Author: Patrick-Christopher Mattulat
  3. * Company: Lynar Studios
  4. * E-Mail: webmaster@lynarstudios.com
  5. * Created: 2020-08-14
  6. * Changed: 2023-02-23
  7. *
  8. * */
  9. #include <iomanip>
  10. #include <ls-std/time/Date.hpp>
  11. #if defined(_WIN32) || defined(__APPLE__)
  12. #include <sstream> // only MSVC and Apple need this
  13. #endif
  14. using ls::std::core::Class;
  15. using ls::std::time::Date;
  16. using std::localtime;
  17. using std::put_time;
  18. using std::string;
  19. using std::stringstream;
  20. using std::time;
  21. Date::Date() : Class("Date")
  22. {
  23. this->timestamp = ::time(nullptr);
  24. this->_init();
  25. }
  26. Date::~Date() noexcept = default;
  27. Date &Date::operator+(int _value)
  28. {
  29. this->_incrementByDays(_value);
  30. return *this;
  31. }
  32. Date &Date::operator-(int _value)
  33. {
  34. this->_decrementByDays(_value);
  35. return *this;
  36. }
  37. Date &Date::operator+=(int _value)
  38. {
  39. this->_incrementByDays(_value);
  40. return *this;
  41. }
  42. Date &Date::operator-=(int _value)
  43. {
  44. this->_decrementByDays(_value);
  45. return *this;
  46. }
  47. bool Date::after(const Date &_foreignDate) const
  48. {
  49. return this->timestamp > _foreignDate.getTime();
  50. }
  51. bool Date::before(const Date &_foreignDate) const
  52. {
  53. return this->timestamp < _foreignDate.getTime();
  54. }
  55. int Date::getDay()
  56. {
  57. return this->localTime->tm_mday;
  58. }
  59. int Date::getHour()
  60. {
  61. return this->localTime->tm_hour;
  62. }
  63. int Date::getMinute()
  64. {
  65. return this->localTime->tm_min;
  66. }
  67. int Date::getMonth()
  68. {
  69. return this->localTime->tm_mon + 1;
  70. }
  71. int Date::getSecond()
  72. {
  73. return this->localTime->tm_sec;
  74. }
  75. int Date::getYear()
  76. {
  77. return this->localTime->tm_year + 1900;
  78. }
  79. time_t Date::getTime() const
  80. {
  81. return this->timestamp;
  82. }
  83. void Date::setTime(time_t _timestamp)
  84. {
  85. this->timestamp = _timestamp;
  86. this->_init();
  87. }
  88. string Date::toString()
  89. {
  90. stringstream _stream{};
  91. _stream << put_time(this->localTime, "%Y-%m-%d %H:%M:%S");
  92. return _stream.str();
  93. }
  94. void Date::_decrementByDays(int _value)
  95. {
  96. this->timestamp -= (_value * 86400);
  97. }
  98. void Date::_incrementByDays(int _value)
  99. {
  100. this->timestamp += (_value * 86400);
  101. }
  102. void Date::_init()
  103. {
  104. this->localTime = localtime(&this->timestamp);
  105. }