71 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			C++
		
	
	
	
	
	
			
		
		
	
	
			71 lines
		
	
	
		
			2.2 KiB
		
	
	
	
		
			C++
		
	
	
	
	
	
| /*
 | |
|  * @brief Defines and implements functions to handle timestamps
 | |
|  * @file helper/UtcTime.h
 | |
|  * @author Sven Czarnian <devel@svcz.de>
 | |
|  * @copyright Copyright 2020-2021 Sven Czarnian
 | |
|  * @license This project is published under the GNU General Public License v3 (GPLv3)
 | |
|  */
 | |
| 
 | |
| #pragma once
 | |
| 
 | |
| #include <ctime>
 | |
| #include <chrono>
 | |
| #include <sstream>
 | |
| #include <string>
 | |
| #include <iomanip>
 | |
| 
 | |
| namespace aman {
 | |
|     /**
 | |
|      * @brief Defines helper functions to handle system timestamps and UTC timestamps
 | |
|      * @ingroup helper
 | |
|      */
 | |
|     class UtcTime {
 | |
|     public:
 | |
|         using Point = std::chrono::utc_clock::time_point;
 | |
| 
 | |
|         UtcTime() = delete;
 | |
|         UtcTime(const UtcTime&) = delete;
 | |
|         UtcTime(UtcTime&&) = delete;
 | |
|         UtcTime& operator=(const UtcTime&) = delete;
 | |
|         UtcTime& operator=(UtcTime&&) = delete;
 | |
| 
 | |
|         /**
 | |
|          * @brief Returns the current time in UTC
 | |
|          * @return The current UTC time
 | |
|          */
 | |
|         static __inline Point currentUtc() {
 | |
|             return std::chrono::utc_clock::now();
 | |
|         }
 | |
| 
 | |
|         /**
 | |
|          * @brief Converts a string into a std::chrono::system_clock::time_point in UTC
 | |
|          * @param[in] date The string containing the timepoint
 | |
|          * @return The converted time
 | |
|          */
 | |
|         static __inline Point stringToTime(const std::string& date) {
 | |
|             Point retval;
 | |
|             std::stringstream stream(date);
 | |
|             std::chrono::from_stream(stream, "%Y-%m-%d %X", retval);
 | |
|             return retval;
 | |
|         }
 | |
| 
 | |
|         /**
 | |
|          * @brief Converts a time point into a string
 | |
|          * The function converts into the following format:
 | |
|          * - %y%m%d%H%M
 | |
|          * @param[in] time The timepoint which needs to be converted in UTC
 | |
|          * @return The converted time
 | |
|          */
 | |
|         static __inline std::string timeToString(const Point& time, const std::string& format = "%Y-%m-%d %X") {
 | |
|             if ((std::chrono::time_point<std::chrono::utc_clock>::max)() != time) {
 | |
|                 std::stringstream stream;
 | |
|                 stream << std::format("{0:" + format + "}", time);
 | |
|                 return stream.str();
 | |
|             }
 | |
|             else {
 | |
|                 return "";
 | |
|             }
 | |
|         }
 | |
|     };
 | |
| }
 |