OdbDesign
OdbDesign ODB++ Parser - C++ library, gRPC/REST server, CLI, tests
 
Loading...
Searching...
No Matches
timestamp.cpp
Go to the documentation of this file.
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
12using namespace std::chrono;
13
14namespace Utils
15{
16 const int MS_PER_S = 1000;
17
18 std::string make_timestamp(const system_clock::time_point& timepoint)
19 {
20 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 if (localtime_r(&tp_time_t, &tm_result) == nullptr) return "";
27#endif
28
29 auto ms = duration_cast<milliseconds>(timepoint.time_since_epoch()) % MS_PER_S;
30
31 std::stringstream ss;
32 // date and time
33 ss << std::put_time(&tm_result, "%D %T");
34 // add ms
35 ss << '.' << std::setfill('0') << std::setw(3) << ms.count();
36 return ss.str();
37 }
38
39 std::string make_timestamp()
40 {
41 return make_timestamp(system_clock::now());
42 }
43
44 system_clock::time_point parse_timestamp(const std::string& timestamp, const std::string& format)
45 {
46 struct tm tm{};
47 std::istringstream ss(timestamp);
48 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 auto tp = system_clock::from_time_t(std::mktime(&tm));
57 return tp;
58 }
59}
const int MS_PER_S
Definition timestamp.cpp:16
std::string make_timestamp()
Definition timestamp.cpp:39
system_clock::time_point parse_timestamp(const std::string &timestamp, const std::string &format)
Definition timestamp.cpp:44