-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtime_utils.cpp
More file actions
274 lines (239 loc) · 7.02 KB
/
time_utils.cpp
File metadata and controls
274 lines (239 loc) · 7.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// Copyright 2021 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file time_utils.cpp
*
*/
#include <iomanip>
#include <thread>
#include <sstream>
#include <cpp_utils/macros/macros.hpp>
#include <cpp_utils/time/time_utils.hpp>
#include <cpp_utils/exception/PreconditionNotMet.hpp>
#include <cpp_utils/exception/ValueNotAllowedException.hpp>
#include <cpp_utils/Log.hpp>
// These functions has different names in windows
#if _EPROSIMA_WINDOWS_PLATFORM
#define timegm _mkgmtime
#endif // if _EPROSIMA_WINDOWS_PLATFORM
namespace eprosima {
namespace utils {
static std::string utc_offset_string(
const std::tm& tm,
bool local_time)
{
if (!local_time)
{
return "UTC+00";
}
std::ostringstream os;
os << std::put_time(&tm, "%z");
const std::string z = os.str();
if (z.empty() || (z[0] != '+' && z[0] != '-'))
{
return "UTC+00";
}
std::string hh;
std::string mm = "00";
// +HH
if (z.size() == 3)
{
hh = z.substr(1, 2);
}
// +HHMM
else if (z.size() == 5)
{
hh = z.substr(1, 2);
mm = z.substr(3, 2);
}
// +HH:MM
else if (z.size() == 6 && z[3] == ':')
{
hh = z.substr(1, 2);
mm = z.substr(4, 2);
}
else
{
return "UTC+00";
}
std::string ret = "UTC";
ret += z[0];
ret += hh;
if (mm != "00")
{
ret += ":";
ret += mm;
}
return ret;
}
Timestamp now() noexcept
{
return Timeclock::now();
}
Timestamp the_end_of_time() noexcept
{
return Timestamp::max();
}
Timestamp the_beginning_of_time() noexcept
{
return Timestamp::min();
}
Timestamp date_to_timestamp(
unsigned int year,
unsigned int month,
unsigned int day,
unsigned int hour /* = 0 */,
unsigned int minute /* = 0 */,
unsigned int second /* = 0 */)
{
std::tm tm;
tm.tm_sec = static_cast<int>(second);
tm.tm_min = static_cast<int>(minute);
tm.tm_hour = static_cast<int>(hour);
tm.tm_mday = static_cast<int>(day);
tm.tm_mon = static_cast<int>(month) - 1;
tm.tm_year = static_cast<int>(year) - 1900;
return Timeclock::from_time_t(normalize(timegm(&tm)));
}
Timestamp time_to_timestamp(
unsigned int hour /* = 0 */,
unsigned int minute /* = 0 */,
unsigned int second /* = 0 */)
{
std::tm tm;
// Initialise with current timestamp to set date
time_t duration_seconds = normalize(Timeclock::to_time_t(now()));
tm = *std::gmtime(&duration_seconds);
tm.tm_sec = static_cast<int>(second);
tm.tm_min = static_cast<int>(minute);
tm.tm_hour = static_cast<int>(hour);
return Timeclock::from_time_t(timegm(&tm));
}
std::string timestamp_to_string(
const Timestamp& timestamp,
const std::string& format /* = "%Z_%Y-%m-%d_%H-%M-%S" */,
bool local_time /* = false */)
{
std::ostringstream ss;
time_t duration_seconds = normalize(Timeclock::to_time_t(timestamp));
std::tm* tm = nullptr;
if (local_time)
{
tm = std::localtime(&duration_seconds);
}
else
{
tm = std::gmtime(&duration_seconds);
}
if (tm)
{
// Replace %Z with a cross-platform "UTC+HH" / "UTC+HH:MM" offset string.
// Standard %Z is platform-dependent: on Windows it outputs full localized names,
// while on Linux it outputs short abbreviations.
std::string processed_format;
processed_format.reserve(format.size() + 16);
for (std::size_t i = 0; i < format.size(); ++i)
{
if (format[i] == '%' && i + 1 < format.size() && format[i + 1] == 'Z')
{
processed_format += utc_offset_string(*tm, local_time);
++i;
}
else
{
processed_format += format[i];
}
}
ss << std::put_time(tm, processed_format.c_str());
}
else
{
// gmtime/localtime() returned null
throw PreconditionNotMet(STR_ENTRY << "Format <" << format << "> to convert Timestamp to string is incorrect.");
}
return ss.str();
}
Timestamp string_to_timestamp(
const std::string& timestamp,
const std::string& format /* = "%Z_%Y-%m-%d_%H-%M-%S" */,
bool local_time /* = false */)
{
std::istringstream ss(timestamp);
std::tm tm{};
ss >> std::get_time(&tm, format.c_str());
if (ss.fail())
{
throw PreconditionNotMet(
STR_ENTRY << "Format <" << format << "> to convert string to Timestamp is not valid for timestamp "
<< timestamp << ".");
}
std::time_t utc_time;
if (local_time)
{
// Attempt to automatically determine if DST in effect
tm.tm_isdst = -1;
// WARNING: might not be available in all systems, mktime sets this value to 0/1 if succesfully found this info
utc_time = std::mktime(&tm);
if (tm.tm_isdst < 0)
{
logWarning(
UTILS_TIME,
"DST information could not be found in the system, converted timestamp might be an hour off.");
}
}
else
{
utc_time = timegm(&tm);
}
if ((time_t)-1 == utc_time)
{
throw ValueNotAllowedException(
STR_ENTRY << "Failed to convert string to timestamp");
}
return Timeclock::from_time_t(utc_time);
}
std::chrono::milliseconds duration_to_ms(
const Duration_ms& duration) noexcept
{
return std::chrono::milliseconds(duration);
}
void sleep_for(
const Duration_ms& sleep_time) noexcept
{
std::this_thread::sleep_for(duration_to_ms(sleep_time));
}
time_t normalize(
const time_t& time) noexcept
{
time_t normalized_time = time;
#if _EPROSIMA_WINDOWS_PLATFORM // In Windows std::gmtime does not support negative values
time_t max_value;
#if _PLATFORM_64BIT
max_value = 32535215999; // In WIN64, max value is 3000-12-31_23-59-59
#else
max_value = std::numeric_limits<int32_t>::max(); // In WIN32, values greater than 2^32 are not supported
#endif // if PLATFORM_64BIT
if (0 > time || time > max_value)
{
EPROSIMA_LOG_WARNING(TIME_UTILS,
"Timestamp value: "
<< time << " is out of range for Windows, clamping to 0 and "
<< max_value);
normalized_time = std::max((time_t) 0, std::min(max_value, time));
}
#endif // if _EPROSIMA_WINDOWS_PLATFORM
return normalized_time;
}
} /* namespace utils */
} /* namespace eprosima */