DateTime.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <vector>
  2. #include "stringtools.h"
  3. #include "Exception.h"
  4. #include "DateTime.h"
  5. using namespace std;
  6. void DateTime::get(int& year, int& month, int& mday,
  7. int& hour, int& min, int& sec) const
  8. {
  9. tm* ltm = localtime(&theTime);
  10. year = 1900 + ltm->tm_year;
  11. month = 1 + ltm->tm_mon;
  12. mday = ltm->tm_mday;
  13. hour = ltm->tm_hour;
  14. min = ltm->tm_min;
  15. sec = ltm->tm_sec;
  16. }
  17. DateTime::DateTime(int Y, int M, int D, int h, int m, int s)
  18. {
  19. struct tm ltm;
  20. ltm.tm_year = Y - 1900;
  21. ltm.tm_mon = M - 1;
  22. ltm.tm_mday = D;
  23. ltm.tm_min = m;
  24. ltm.tm_hour = h;
  25. ltm.tm_sec = s;
  26. ltm.tm_isdst = -1;
  27. theTime = mktime(&ltm);
  28. }
  29. #if 0
  30. struct tm
  31. {
  32. int tm_sec; /* Seconds (0-60) */
  33. int tm_min; /* Minutes (0-59) */
  34. int tm_hour; /* Hours (0-23) */
  35. int tm_mday; /* Day of the month (1-31) */
  36. int tm_mon; /* Month (0-11) */
  37. int tm_year; /* Year - 1900 */
  38. int tm_wday; /* Day of the week (0-6, Sunday = 0) */
  39. int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */
  40. int tm_isdst; /* Daylight saving time */
  41. };
  42. #endif
  43. bool DateTime::match(const set<int>& Y, const set<int>& M, const set<int>& D,
  44. const set<int>& W,
  45. const set<int>& h, const set<int>& m, const set<int>& s)
  46. {
  47. tm* tm = localtime(&theTime);
  48. return match(Y, tm->tm_year) &&
  49. match(M, tm->tm_mon - 1) &&
  50. match(D, tm->tm_mday) &&
  51. match(W, tm->tm_wday) &&
  52. match(h, tm->tm_hour) &&
  53. match(m, tm->tm_min) &&
  54. match(s, tm->tm_sec);
  55. }
  56. using std::to_string;
  57. std::string DateTime::toString2(int v)
  58. {
  59. std::string res = to_string(v);
  60. if (res.size() < 2)
  61. res = "0" + res;
  62. return res;
  63. }
  64. std::string DateTime::getString(char typ) const
  65. {
  66. int y, mo, d, h, mi, s;
  67. get(y, mo, d, h, mi, s);
  68. switch (typ)
  69. {
  70. case 'h': // human (german)
  71. return to_string(d) + "." + to_string(mo) + "." + to_string(y) + " " +
  72. toString2(h) + ':' + toString2(mi) + ':' + toString2(s);
  73. case 'm': // machine
  74. return toString2(y) + "-" + toString2(mo) + "-" + toString2(d) + "-" +
  75. toString2(h) + '-' + toString2(mi) + '-' + toString2(s);
  76. case 's': // short machine
  77. return toString2(y) + "-" + toString2(mo) + "-" + toString2(d) + "-" +
  78. toString2(h);
  79. std::to_string(h);
  80. }
  81. throw Exception("DateTime", "wrong string format type");
  82. }