time.hpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #pragma once
  2. #include <chrono>
  3. #include <string>
  4. #include <iostream>
  5. #include <iomanip>
  6. class TimeTool {
  7. public:
  8. enum TemporalPrecision {
  9. TemporalPrecisionYear = 0,
  10. TemporalPrecisionMount = 4,
  11. TemporalPrecisionDay = 6,
  12. TemporalPrecisionHour = 8,
  13. TemporalPrecisionMin = 10,
  14. TemporalPrecisionSec = 12,
  15. TemporalPrecisionMs = 15,
  16. };
  17. public:
  18. static std::string timeDropoutStr(TemporalPrecision begain = TemporalPrecisionMs, TemporalPrecision end = TemporalPrecisionYear) {
  19. std::stringstream time;
  20. std::string t = getTime();
  21. int max = begain;
  22. int min = end;
  23. if (begain == TemporalPrecisionYear) {
  24. max += 3;
  25. } else if (begain == TemporalPrecisionMs) {
  26. max += 2;
  27. } else {
  28. max +=1;
  29. }
  30. for (int i = min; i < max; i++) {
  31. time << t[i];
  32. }
  33. t.clear();
  34. time >> t;
  35. return t;
  36. }
  37. static unsigned long long timeDropoutLL(TemporalPrecision begain = TemporalPrecisionMs, TemporalPrecision end = TemporalPrecisionYear) {
  38. std::string str = timeDropoutStr(begain, end);
  39. if (str.empty()) {
  40. return 0;
  41. }
  42. unsigned long long time_dropout = std::stoull(str);
  43. return time_dropout;
  44. }
  45. private:
  46. static std::string getTime() {
  47. auto now = std::chrono::system_clock::now();
  48. auto timet = std::chrono::system_clock::to_time_t(now);
  49. auto localTime = *std::gmtime(&timet);
  50. auto ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now).time_since_epoch().count() % 1000;
  51. std::stringstream ss;
  52. std::string str;
  53. ss << std::put_time(&localTime, "%Y%m%d%H%M%S") << std::setfill('0') << std::setw(3) << ms;
  54. ss >> str;
  55. return str;
  56. }
  57. };