2 * @brief Parse and format date/time strings
4 /* Copyright (c) 2013,2014,2015,2016,2019 Olly Betts
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
37 parse_datetime(const string
& s
)
40 const char * p
= s
.c_str();
42 if (s
.find('T') != string::npos
|| s
.find('-') != string::npos
) {
43 // E.g. "2013-01-17T09:10:55Z"
44 t
.tm_year
= strtoul(p
, &q
, 10) - 1900;
47 t
.tm_mon
= strtoul(p
+ 1, &q
, 10) - 1;
53 t
.tm_mday
= strtoul(p
+ 1, &q
, 10);
59 t
.tm_hour
= strtoul(p
+ 1, &q
, 10);
62 t
.tm_min
= strtoul(p
+ 1, &q
, 10);
68 t
.tm_sec
= strtoul(p
+ 1, &q
, 10);
74 t
.tm_hour
= t
.tm_min
= t
.tm_sec
= 0;
77 // FIXME: always assume UTC for now...
80 // As produced by LibreOffice HTML export.
82 // "20130117;09105500" == 2013-01-17T09:10:55
83 // "20070903;200000000000" == 2007-09-03T00:02:00
84 // "20070831;5100000000000" == 2007-08-31T00:51:00
85 unsigned long v
= strtoul(p
, &q
, 10);
87 // LibreOffice sometimes exports "0;0". A date of "0" is
94 t
.tm_mon
= v
% 100 - 1;
95 t
.tm_year
= v
/ 100 - 1900;
98 v
= strtoul(p
, &q
, 10);
99 v
/= (q
- p
> 10) ? 1000000000 : 100;
105 t
.tm_hour
= t
.tm_min
= t
.tm_sec
= 0;
113 // Write exactly w chars to buffer p representing integer v.
115 // The result is left padded with zeros if v < pow(10, w - 1).
117 // If v >= pow(10, w), then the output will show v % pow(10, w) (i.e. the
118 // most significant digits are lost).
120 format_int_fixed_width(char* p
, int v
, int w
)
123 p
[w
] = '0' + (v
% 10);
129 date_to_string(int year
, int month
, int day
)
131 year
= std::clamp(year
, 0, 9999);
132 month
= std::clamp(month
, 1, 12);
133 day
= std::clamp(day
, 1, 31);
135 format_int_fixed_width(buf
, year
, 4);
136 format_int_fixed_width(buf
+ 4, month
, 2);
137 format_int_fixed_width(buf
+ 6, day
, 2);
138 return string(buf
, 8);