UtcTime.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * @brief Defines and implements functions to handle timestamps
  3. * @file helper/UtcTime.h
  4. * @author Sven Czarnian <devel@svcz.de>
  5. * @copyright Copyright 2020-2021 Sven Czarnian
  6. * @license This project is published under the GNU General Public License v3 (GPLv3)
  7. */
  8. #pragma once
  9. #include <ctime>
  10. #include <chrono>
  11. #include <sstream>
  12. #include <string>
  13. #include <iomanip>
  14. namespace aman {
  15. /**
  16. * @brief Defines helper functions to handle system timestamps and UTC timestamps
  17. * @ingroup helper
  18. */
  19. class UtcTime {
  20. public:
  21. using Point = std::chrono::utc_clock::time_point;
  22. UtcTime() = delete;
  23. UtcTime(const UtcTime&) = delete;
  24. UtcTime(UtcTime&&) = delete;
  25. UtcTime& operator=(const UtcTime&) = delete;
  26. UtcTime& operator=(UtcTime&&) = delete;
  27. /**
  28. * @brief Returns the current time in UTC
  29. * @return The current UTC time
  30. */
  31. static __inline Point currentUtc() {
  32. return std::chrono::utc_clock::now();
  33. }
  34. /**
  35. * @brief Converts a string into a std::chrono::system_clock::time_point in UTC
  36. * @param[in] date The string containing the timepoint
  37. * @return The converted time
  38. */
  39. static __inline Point stringToTime(const std::string& date) {
  40. Point retval;
  41. std::stringstream stream(date);
  42. std::chrono::from_stream(stream, "%Y-%m-%d %X", retval);
  43. return retval;
  44. }
  45. /**
  46. * @brief Converts a time point into a string
  47. * The function converts into the following format:
  48. * - %y%m%d%H%M
  49. * @param[in] time The timepoint which needs to be converted in UTC
  50. * @return The converted time
  51. */
  52. static __inline std::string timeToString(const Point& time, const std::string& format = "%Y-%m-%d %X") {
  53. if ((std::chrono::time_point<std::chrono::utc_clock>::max)() != time) {
  54. std::stringstream stream;
  55. stream << std::format("{0:" + format + "}", time);
  56. return stream.str();
  57. }
  58. else {
  59. return "";
  60. }
  61. }
  62. };
  63. }