Line data Source code
1 : //
2 : // Created by nam20485 on 6/12/22.
3 : //
4 :
5 : #include <sstream>
6 : #include <iomanip>
7 : #include <ctime>
8 : #include "timestamp.h"
9 : #include <sstream>
10 : #include <time.h>
11 :
12 : using namespace std::chrono;
13 :
14 : namespace Utils
15 : {
16 : const int MS_PER_S = 1000;
17 :
18 0 : std::string make_timestamp(const system_clock::time_point& timepoint)
19 : {
20 0 : auto tp_time_t = system_clock::to_time_t(timepoint);
21 :
22 : struct tm tm_result;
23 : #ifdef _WIN32
24 : if (localtime_s(&tm_result, &tp_time_t) != 0) return "";
25 : #else
26 0 : if (localtime_r(&tp_time_t, &tm_result) == nullptr) return "";
27 : #endif
28 :
29 0 : auto ms = duration_cast<milliseconds>(timepoint.time_since_epoch()) % MS_PER_S;
30 :
31 0 : std::stringstream ss;
32 : // date and time
33 0 : ss << std::put_time(&tm_result, "%D %T");
34 : // add ms
35 0 : ss << '.' << std::setfill('0') << std::setw(3) << ms.count();
36 0 : return ss.str();
37 0 : }
38 :
39 0 : std::string make_timestamp()
40 : {
41 0 : return make_timestamp(system_clock::now());
42 : }
43 :
44 180 : system_clock::time_point parse_timestamp(const std::string& timestamp, const std::string& format)
45 : {
46 180 : struct tm tm{};
47 180 : std::istringstream ss(timestamp);
48 180 : ss >> std::get_time(&tm, format.c_str());
49 :
50 : #if defined(_DEBUG)
51 : std::stringstream ss2;
52 : ss2 << std::put_time(&tm, "%D %T");
53 : auto s = ss2.str();
54 : #endif // DEBUG
55 :
56 180 : auto tp = system_clock::from_time_t(std::mktime(&tm));
57 180 : return tp;
58 180 : }
59 : }
|