-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheasy_datetime.h
More file actions
590 lines (502 loc) · 22.5 KB
/
easy_datetime.h
File metadata and controls
590 lines (502 loc) · 22.5 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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
#pragma once
#include <array>
#include <string>
#include <chrono>
#include <iomanip>
namespace easy {
namespace datetime {
using std::chrono::hours;
using std::chrono::microseconds;
using std::chrono::milliseconds;
using std::chrono::minutes;
using std::chrono::seconds;
using days =
std::chrono::duration<long long,
std::ratio_multiply<std::ratio<24>, hours::period>>;
using weeks =
std::chrono::duration<long long,
std::ratio_multiply<std::ratio<7>, days::period>>;
using clock = std::chrono::system_clock;
using default_duration = std::chrono::milliseconds;
using timestamp = std::time_t;
/// @brief current(now) time_point
/// @tparam _Duration offset duration type
/// @param offset duration value
/// @return time_point (system_clock)
template <typename _Duration = default_duration>
static constexpr inline clock::time_point current_time_point(
long long offset = 0) noexcept {
return clock::now() + _Duration(offset);
}
/// @brief current(now) time_point
/// @tparam _Rep an arithmetic type representing the number of ticks
/// @tparam _Period a std::ratio representing the tick period (i.e. the number
/// of second's fractions per tick)
/// @param offset offset value
/// @return time_point (system_clock)
template <typename _Rep = long long, typename _Period = std::milli>
static constexpr inline clock::time_point current_time_point(
std::chrono::duration<_Rep, _Period> offset) noexcept {
return clock::now() + offset;
}
/// @brief current(now) timestamp
/// @tparam _Duration duration type
/// @return timestamp of duration's ratio
template <typename _Duration = default_duration>
static constexpr inline timestamp current_timestamp() noexcept {
return std::chrono::duration_cast<_Duration>(
current_time_point<_Duration>().time_since_epoch())
.count();
}
/// @brief relative(now) timestamp
/// @tparam _Duration duration type
/// @tparam _Rep an arithmetic type representing the number of ticks
/// @tparam _Period a std::ratio representing the tick period (i.e. the number
/// of second's fractions per tick)
/// @param offset offset value
/// @return timestamp of duration's ratio
template <typename _Duration = default_duration, typename _Rep = long long,
typename _Period = std::milli>
static constexpr inline timestamp relative_timestamp(
std::chrono::duration<_Rep, _Period> offset) noexcept {
return std::chrono::duration_cast<_Duration>(
current_time_point(offset).time_since_epoch())
.count();
}
/// @brief current(now) timestamp of day start
/// @tparam _Duration duration type
/// @return timestamp of duration's ratio
template <typename _Duration = default_duration>
static constexpr inline timestamp current_days_timestamp() noexcept {
return std::chrono::duration_cast<_Duration>(
std::chrono::duration_cast<days>(
current_time_point<_Duration>().time_since_epoch()))
.count();
}
/// @brief relative(now) timestamp of day start
/// @tparam _Duration duration type
/// @tparam _Rep an arithmetic type representing the number of ticks
/// @tparam _Period a std::ratio representing the tick period (i.e. the number
/// of second's fractions per tick)
/// @param offset offset value
/// @return timestamp of duration's ratio
template <typename _Duration = default_duration, typename _Rep = long long,
typename _Period = std::milli>
static constexpr inline timestamp relative_days_timestamp(
std::chrono::duration<_Rep, _Period> offset) noexcept {
return std::chrono::duration_cast<_Duration>(
std::chrono::duration_cast<days>(
current_time_point(offset).time_since_epoch()))
.count();
}
/// @brief current(now) timestamp of hour start
/// @tparam _Duration duration type
/// @return timestamp of duration's ratio
template <typename _Duration = default_duration>
static constexpr inline timestamp current_hours_timestamp() noexcept {
return std::chrono::duration_cast<_Duration>(
std::chrono::duration_cast<hours>(
current_time_point<_Duration>().time_since_epoch()))
.count();
}
/// @brief relative(now) timestamp of hour start
/// @tparam _Duration duration type
/// @tparam _Rep an arithmetic type representing the number of ticks
/// @tparam _Period a std::ratio representing the tick period (i.e. the number
/// of second's fractions per tick)
/// @param offset offset value
/// @return timestamp of duration's ratio
template <typename _Duration = default_duration, typename _Rep = long long,
typename _Period = std::milli>
static constexpr inline timestamp relative_hours_timestamp(
std::chrono::duration<_Rep, _Period> offset) noexcept {
return std::chrono::duration_cast<_Duration>(
std::chrono::duration_cast<hours>(
current_time_point(offset).time_since_epoch()))
.count();
}
/// @brief current(now) timestamp of minutes start
/// @tparam _Duration duration type
/// @return timestamp of duration's ratio
template <typename _Duration = default_duration>
static constexpr inline timestamp current_minutes_timestamp() noexcept {
return std::chrono::duration_cast<_Duration>(
std::chrono::duration_cast<minutes>(
current_time_point<_Duration>().time_since_epoch()))
.count();
}
/// @brief relative(now) timestamp of minutes start
/// @tparam _Duration duration type
/// @tparam _Rep an arithmetic type representing the number of ticks
/// @tparam _Period a std::ratio representing the tick period (i.e. the number
/// of second's fractions per tick)
/// @param offset offset value
/// @return timestamp of duration's ratio
template <typename _Duration = default_duration, typename _Rep = long long,
typename _Period = std::milli>
static constexpr inline timestamp relative_minutes_timestamp(
std::chrono::duration<_Rep, _Period> offset) noexcept {
return std::chrono::duration_cast<_Duration>(
std::chrono::duration_cast<minutes>(
current_time_point(offset).time_since_epoch()))
.count();
}
/// @brief timestamp to time_point(system clock)
/// @tparam _Duration duration type
/// @param ts timestamp
/// @return time_point(system clock)
template <typename _Duration = default_duration>
static constexpr clock::time_point from_timestamp(timestamp ts) {
return clock::time_point(_Duration(ts));
}
// ... low performance ...
// static constexpr char default_format[] = "%Y-%m-%d %H:%M:%S";
// static constexpr char default_format_ms[] = "%Y-%m-%d %H:%M:%S.%X";
// static inline std::string local_time_string(clock::time_point ctp, bool
// format_ms) {
//
// const std::time_t time_t_ = std::chrono::system_clock::to_time_t(ctp);
//
// const std::tm* tm = std::localtime(&time_t_);
// if (tm == nullptr) return "";
//
// std::ostringstream ss;
// ss << std::put_time(tm, default_format);
// if (format_ms) {
// static constexpr long long ms_ratio = 1000;
// const long long ms =
// std::chrono::duration_cast<std::chrono::milliseconds>(ctp.time_since_epoch()).count()
// % ms_ratio; ss << std::setw(3) << std::setfill('0') << ms;
// }
// return ss.str();
// }
inline constexpr auto localtime_exchanger = [](std::tm& cpt_tm,
timestamp cpt_secs_count) {
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || \
defined(_WIN64) // windows platform
[[maybe_unused]] auto lt_res = localtime_s(&cpt_tm, &cpt_secs_count);
#else // other platforms
[[maybe_unused]] auto lt_res = localtime_r(&cpt_secs_count, &cpt_tm);
#endif
return cpt_tm;
};
inline constexpr auto utctime_exchanger = [](std::tm& cpt_tm,
timestamp cpt_secs_count) {
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || \
defined(_WIN64) // windows platform
[[maybe_unused]] auto lt_res = gmtime_s(&cpt_tm, &cpt_secs_count);
#else // other platforms
[[maybe_unused]] auto lt_res = gmtime_r(&cpt_secs_count, &cpt_tm);
#endif
return cpt_tm;
};
static std::string_view __inner_time_string_v(
clock::time_point ctp, bool format_ms,
std::function<void(std::tm&, timestamp)>&& exchange_time_tm) {
static thread_local bool been_set = false;
static thread_local std::chrono::seconds last_secs{};
static constexpr std::size_t result_size = 32;
static constexpr std::size_t secs_result_size =
19; // length after format seconds
static constexpr std::size_t msecs_result_size =
19 + 4; // length after format seconds + msecs
static constexpr long long ms_ratio = 1000;
// %4d-%02d-%02d %02d:%02d:%02d.%03d
static thread_local char last_secs_result[result_size]{};
std::chrono::system_clock::duration ctp_dur = ctp.time_since_epoch();
std::chrono::seconds cpt_secs =
std::chrono::duration_cast<std::chrono::seconds>(ctp_dur);
if (been_set && last_secs == cpt_secs) {
std::string_view result(last_secs_result, result_size);
if (format_ms) {
const long long ms =
std::chrono::duration_cast<std::chrono::milliseconds>(ctp_dur)
.count() %
ms_ratio;
[[maybe_unused]] auto snf_res_ms =
snprintf(last_secs_result + secs_result_size,
result_size - secs_result_size - 1, ".%03lld", ms);
result.remove_suffix(result_size - msecs_result_size);
}
else {
result.remove_suffix(result_size - secs_result_size);
}
return result;
}
last_secs = cpt_secs;
been_set = true;
static thread_local std::tm cpt_tm = std::tm();
const auto cpt_secs_count = last_secs.count();
exchange_time_tm(cpt_tm, cpt_secs_count);
[[maybe_unused]] auto snf_res = snprintf(
last_secs_result, result_size - 1, "%4d-%02d-%02d %02d:%02d:%02d",
cpt_tm.tm_year + 1900, cpt_tm.tm_mon + 1, cpt_tm.tm_mday, cpt_tm.tm_hour,
cpt_tm.tm_min, cpt_tm.tm_sec);
std::string_view result(last_secs_result, result_size);
if (format_ms) {
const long long ms =
std::chrono::duration_cast<std::chrono::milliseconds>(ctp_dur).count() %
ms_ratio;
[[maybe_unused]] auto snf_res_ms =
snprintf(last_secs_result + secs_result_size,
result_size - secs_result_size - 1, ".%03lld", ms);
result.remove_suffix(result_size - msecs_result_size);
}
else {
result.remove_suffix(result_size - secs_result_size);
}
return result;
}
/// @brief convert to localtime string_view
/// @param ctp source
/// @param format_ms result include ms
/// @return string_view
static inline std::string_view localtime_string_v(clock::time_point ctp,
bool format_ms = true) {
return __inner_time_string_v(ctp, format_ms, localtime_exchanger);
}
/// @brief convert to localtime string
/// @param ctp source
/// @param format_ms result include ms
/// @return string_view
static inline std::string localtime_string(clock::time_point ctp,
bool format_ms = true) {
const auto sv = localtime_string_v(ctp, format_ms);
return std::string{sv.data(), sv.size()};
}
/// @brief convert to utc string_view
/// @param ctp source
/// @param format_ms result include ms
/// @return string_view
static inline std::string_view utc_string_v(clock::time_point ctp,
bool format_ms = true) {
return __inner_time_string_v(ctp, format_ms, utctime_exchanger);
}
/// @brief convert to utc string
/// @param ctp source
/// @param format_ms result include ms
/// @return string_view
static inline std::string utc_string(clock::time_point ctp,
bool format_ms = true) {
const auto sv = utc_string_v(ctp, format_ms);
return std::string{sv.data(), sv.size()};
}
static std::pair<clock::time_point, bool> __inner_from_time_string_v(
std::string_view&& sv, bool future,
std::function<void(std::tm&, timestamp)>&& exchange_time_tm) {
bool days_next = future;
std::chrono::milliseconds convert_msecs = {};
int convert_year = 0;
int convert_month = 0;
int convert_day = 0;
clock::time_point current_ctp = current_time_point();
do {
if (sv.empty()) {
break;
}
static constexpr char ms_split_char = '.';
static constexpr char time_split_char = ':';
static constexpr char empty_split_char = ' ';
static constexpr char date_split_char = '-';
static constexpr std::size_t max_array_size = 8;
std::array<char, max_array_size> last_arr{};
std::size_t last_size = 0;
auto lasts_reset = [&last_arr, &last_size]() {
last_arr.fill(0);
last_size = 0;
};
lasts_reset();
static thread_local std::vector<int> result_ms{};
static thread_local std::vector<int> result_time{};
static thread_local std::vector<int> result_date{};
result_ms.reserve(3);
result_ms.clear();
result_time.reserve(3);
result_time.clear();
result_date.reserve(3);
result_date.clear();
auto* result_end = &result_ms;
static constexpr std::size_t ok_date_size = 3;
auto iter = sv.begin();
while (iter != sv.end()) {
if (last_size == max_array_size)
return {clock::time_point{}, false};
switch (*iter) {
case ms_split_char: {
result_end = &result_ms;
result_time.emplace_back(strtol(last_arr.data(), nullptr, 10));
lasts_reset();
} break;
case empty_split_char: {
result_end = &result_time;
result_date.emplace_back(strtol(last_arr.data(), nullptr, 10));
lasts_reset();
} break;
case time_split_char: {
result_end = &result_time;
result_time.emplace_back(strtol(last_arr.data(), nullptr, 10));
lasts_reset();
} break;
case date_split_char: {
result_end = &result_date;
result_date.emplace_back(strtol(last_arr.data(), nullptr, 10));
lasts_reset();
} break;
default:
last_arr[last_size++] = *iter;
break;
}
if (++iter == sv.end()) {
result_end->emplace_back(strtol(last_arr.data(), nullptr, 10));
}
}
static constexpr std::array<long long, 3> time_to_msecs{
3600 * 1000ll, 60 * 1000ll, 1000ll};
if (!result_ms.empty()) {
convert_msecs += std::chrono::milliseconds(result_ms.at(0));
}
auto time_iter = result_time.begin();
for (const auto& one : time_to_msecs) {
if (time_iter == result_time.end())
break;
convert_msecs += std::chrono::milliseconds((*time_iter) * one);
++time_iter;
}
if (result_date.size() == ok_date_size) {
convert_year = result_date.at(0);
convert_month = result_date.at(1);
convert_day = result_date.at(2);
days_next &= false;
}
else {
std::tm cpt_tm = std::tm();
const auto cpt_secs_count =
std::chrono::duration_cast<std::chrono::seconds>(
current_ctp.time_since_epoch())
.count();
exchange_time_tm(cpt_tm, cpt_secs_count);
convert_day = cpt_tm.tm_mday;
convert_month = cpt_tm.tm_mon + 1;
convert_year = cpt_tm.tm_year + 1900;
days_next &= true;
}
} while (false);
std::tm convert_tm = std::tm();
convert_tm.tm_year = convert_year - 1900;
convert_tm.tm_mon = convert_month - 1;
convert_tm.tm_mday = convert_day;
clock::time_point ctp = clock::from_time_t(std::mktime(&convert_tm));
if (days_next && ctp + convert_msecs < current_ctp) {
return {ctp + convert_msecs + days(1), true};
}
return {ctp + convert_msecs, true};
}
/// @brief complex exchange to time_point
/// @tparam future_point_vv fixed to future
/// @param source formatted string
/// @return pair<time_point, is success>
/// 2021-03-03 11:22:33.12 -> millisecs = 12 time_point
/// 2021-03-03 11:22:33 -> millisecs = 0 time_point
/// 2021-03-03 11:22 -> seconds = 0 time_point
/// 2021-03-03 11 -> minutes = 0 time_point
/// 2021-03-03 -> hours = 0 time_point
/// 01:02:03.456 -> current date & 01:02:03.456 time_point
/// 01:02:03 -> current date & 01:02:03 time_point
/// (next day if result time_point < current_time_point && template value
/// future_point_vv == true.
/// eg. current="2024-08-08 10:00:00", source="08:00:00": result="2024-08-09 08:00:00"
/// )
template <bool future_point_vv = false>
static inline constexpr std::pair<clock::time_point, bool>
from_local_time_string(const char* source) {
return __inner_from_time_string_v(std::string_view(source), future_point_vv,
localtime_exchanger);
}
//////////////////////////////////////////////////////////////////////////
/// timespan
template <typename ret_duration_tt>
static constexpr ret_duration_tt timespan(clock::time_point left,
clock::time_point right) {
return std::chrono::duration_cast<ret_duration_tt>(left - right);
}
template <typename ret_duration_tt>
static constexpr ret_duration_tt timespan(timestamp left, timestamp right) {
return timespan<ret_duration_tt>(from_timestamp(left), from_timestamp(right));
}
template <typename ret_duration_tt = default_duration>
static constexpr long long timespan_count(clock::time_point left,
clock::time_point right) {
return timespan<ret_duration_tt>(left - right).count();
}
template <typename ret_duration_tt>
static constexpr long long timespan_count(timestamp left, timestamp right) {
return timespan_count<ret_duration_tt>(from_timestamp(left),
from_timestamp(right));
}
} // namespace datetime
}; // namespace easy
/*
*
std::cout << std::chrono::hours::period::num << std::endl;
std::cout << easy::datetime::days::period::num << std::endl;
std::cout << easy::datetime::current_days_timestamp() << std::endl;
{
static thread_local char xx[32]{ "2021-03-03 11:22:33\0" };
std::string xx_str = "2021-03-03 11:22:33";
std::string_view format = "%Y-%m-%d %H:%M:%S";
timer_cost cost;
for (int i = 0; i < 10000; ++i) {
get_time(xx_str, format);
}
cost.print("sys");
for (int i = 0; i < 10000; ++i) {
easy::datetime::from_local_string(xx);
}
cost.print("easy");
}
{
static thread_local char xx[32]{ "01:02:03.456\0" };
auto ctp = easy::datetime::from_local_string<true>(xx);
std::cout << easy::datetime::localtime_string(ctp.first) << std::endl;
}
{
static thread_local char xx[32]{ "5:0:0\0" };
auto ctp = easy::datetime::from_local_string<true>(xx);
std::cout << easy::datetime::localtime_string(ctp.first) << std::endl;
}
{
static thread_local char xx[32]{ "2021-01-2 11\0" };
auto ctp = easy::datetime::from_local_string<true>(xx);
std::cout << easy::datetime::localtime_string(ctp.first) << std::endl;
}
std::cout << easy::datetime::localtime_string(easy::datetime::current_time_point()).data() << std::endl;
Sleep(1000);
std::cout << easy::datetime::localtime_string(easy::datetime::current_time_point()).data() << std::endl;
std::cout << "----------------------------------------------------------------------" << std::endl;
auto _00 = easy::datetime::from_timestamp<std::chrono::seconds>(0); // 1970-01-01 00:00:00
auto _01 = easy::datetime::from_timestamp<std::chrono::seconds>(57600); // +16 hours
auto _02 = easy::datetime::from_timestamp<std::chrono::seconds>(86400); // +24 hours
auto _03 = easy::datetime::from_timestamp<std::chrono::seconds>(90000); // +25 hours
auto _04 = easy::datetime::from_timestamp<std::chrono::seconds>(144000); // +1 days 16 hours
auto _05 = easy::datetime::from_timestamp<std::chrono::seconds>(172800); // +2 days
auto _06 = easy::datetime::from_timestamp<std::chrono::seconds>(28800 - 28800); // 0
auto _07 = easy::datetime::from_timestamp<std::chrono::seconds>(57600 - 28800); // +16 hours - 8 hours
auto _08 = easy::datetime::from_timestamp<std::chrono::seconds>(86400 - 28800); // +24 hours - 8 hours
auto _09 = easy::datetime::from_timestamp<std::chrono::seconds>(90000 - 28800); // +25 hours - 8 hours
auto _10 = easy::datetime::from_timestamp<std::chrono::seconds>(144000 - 28800); // +40 hours - 8 hours
auto _11 = easy::datetime::from_timestamp<std::chrono::seconds>(172800 - 28800); // +48 hours - 8 hours
std::cout << "local: " << easy::datetime::localtime_string(_00) << " utc: " << easy::datetime::utc_string(_00) << " // 0" << std::endl;
std::cout << "local: " << easy::datetime::localtime_string(_01) << " utc: " << easy::datetime::utc_string(_01) << " // +16 hours" << std::endl;
std::cout << "local: " << easy::datetime::localtime_string(_02) << " utc: " << easy::datetime::utc_string(_02) << " // +24 hours" << std::endl;
std::cout << "local: " << easy::datetime::localtime_string(_03) << " utc: " << easy::datetime::utc_string(_03) << " // +25 hours" << std::endl;
std::cout << "local: " << easy::datetime::localtime_string(_04) << " utc: " << easy::datetime::utc_string(_04) << " // +1 days 16 hours" << std::endl;
std::cout << "local: " << easy::datetime::localtime_string(_05) << " utc: " << easy::datetime::utc_string(_05) << " // +2 days" << std::endl;
std::cout << "local: " << easy::datetime::localtime_string(_06) << " utc: " << easy::datetime::utc_string(_06) << " // 0" << std::endl;
std::cout << "local: " << easy::datetime::localtime_string(_07) << " utc: " << easy::datetime::utc_string(_07) << " // +16 hours - 8 hours" << std::endl;
std::cout << "local: " << easy::datetime::localtime_string(_08) << " utc: " << easy::datetime::utc_string(_08) << " // +24 hours - 8 hours" << std::endl;
std::cout << "local: " << easy::datetime::localtime_string(_09) << " utc: " << easy::datetime::utc_string(_09) << " // +25 hours - 8 hours" << std::endl;
std::cout << "local: " << easy::datetime::localtime_string(_10) << " utc: " << easy::datetime::utc_string(_10) << " // +40 hours - 8 hours" << std::endl;
std::cout << "local: " << easy::datetime::localtime_string(_11) << " utc: " << easy::datetime::utc_string(_11) << " // +48 hours - 8 hours" << std::endl;
std::cout << "----------------------------------------------------------------------" << std::endl;
*
*/