Volume Cartographer 2.27.0
DateTime.hpp
Go to the documentation of this file.
1#pragma once
2
9#include <chrono>
10#include <cstddef>
11#include <ctime>
12#include <iomanip>
13#include <iostream>
14#include <regex>
15#include <sstream>
16
17namespace volcart
18{
26inline auto DateTime() -> std::string
27{
28 const auto now = std::time(nullptr);
29 const auto* time = std::localtime(&now);
30
31 std::stringstream ss;
32 ss << std::put_time(time, "%Y%m%d%H%M%S");
33 return ss.str();
34}
35
43template <typename Rep, typename Period>
44auto DurationToString(std::chrono::duration<Rep, Period> input) -> std::string
45{
46 using namespace std::chrono;
47 using days = duration<int, std::ratio<86400>>;
48 const auto d = duration_cast<days>(input);
49 input -= d;
50 const auto h = duration_cast<hours>(input);
51 input -= h;
52 const auto m = duration_cast<minutes>(input);
53 input -= m;
54 const auto s = duration_cast<seconds>(input);
55
56 const auto dc = d.count();
57 const auto hc = h.count();
58 const auto mc = m.count();
59
60 std::stringstream ss;
61 ss.fill('0');
62 if (dc) {
63 ss << d.count() << "d";
64 }
65 if (dc || hc) {
66 if (dc) {
67 ss << std::setw(2);
68 } // pad if second set of numbers
69 ss << h.count() << "h";
70 }
71 if (dc || hc || mc) {
72 if (dc || hc) {
73 ss << std::setw(2);
74 }
75 ss << m.count() << "m";
76 }
77
78 // Always display seconds
79 if (dc || hc || mc) {
80 ss << std::setw(2);
81 }
82 ss << s.count() << 's';
83
84 return ss.str();
85}
86
96template <typename Duration = std::chrono::milliseconds>
97auto DurationFromString(const std::string& str) -> Duration
98{
99 using namespace std::chrono;
100 const std::regex dReg{
101 R"((\d+h){0,1}(\d+m(?!s)){0,1}(\d+s){0,1}(\d+ms){0,1})"};
102 std::smatch match;
103 Duration d(0);
104 if (std::regex_search(str, match, dReg)) {
105 for (std::size_t i = 1; i < 5; i++) {
106 if (match[i].length() == 0) {
107 continue;
108 }
109 auto part = match[i].str();
110 auto end = (i == 4) ? part.size() - 2 : part.size() - 1;
111 auto val = std::stoi(part.substr(0, end));
112 if (i == 1) {
113 d += std::chrono::hours(val);
114 } else if (i == 2) {
115 d += std::chrono::minutes(val);
116 } else if (i == 3) {
117 d += std::chrono::seconds(val);
118 } else if (i == 4) {
119 d += std::chrono::milliseconds(val);
120 }
121 }
122 } else {
123 throw std::invalid_argument("Cannot parse as duration: " + str);
124 }
125 return d;
126}
127
128} // namespace volcart
Volume Cartographer library
auto DurationFromString(const std::string &str) -> Duration
Convert a duration string to a a std::chrono duration.
Definition: DateTime.hpp:97
auto DateTime() -> std::string
Returns a string representation of the current date and time.
Definition: DateTime.hpp:26
auto DurationToString(std::chrono::duration< Rep, Period > input) -> std::string
Returns a string representation of the provided time duration.
Definition: DateTime.hpp:44