format_timestamp_ms.cpp
1 /*
2  * uuid-log - Microcontroller logging framework
3  * Copyright 2019 Simon Arlott
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #include <uuid/log.h>
20 
21 #include <Arduino.h>
22 
23 #include <cstdint>
24 #include <string>
25 
26 namespace uuid {
27 
28 namespace log {
29 
30 std::string format_timestamp_ms(uint64_t timestamp_ms, unsigned int days_width) {
31  unsigned long days;
32  unsigned int hours, minutes, seconds, milliseconds;
33 
34  days = timestamp_ms / 86400000UL;
35  timestamp_ms %= 86400000UL;
36 
37  hours = timestamp_ms / 3600000UL;
38  timestamp_ms %= 3600000UL;
39 
40  minutes = timestamp_ms / 60000UL;
41  timestamp_ms %= 60000UL;
42 
43  seconds = timestamp_ms / 1000UL;
44  timestamp_ms %= 1000UL;
45 
46  milliseconds = timestamp_ms;
47 
48  std::vector<char> text(10 + 1 /* days */ + 2 + 1 /* hours */ + 2 + 1 /* minutes */ + 2 + 1 /* seconds */ + 3 /* milliseconds */ + 1);
49 
50  snprintf_P(text.data(), text.size(), PSTR("%0*lu+%02u:%02u:%02u.%03u"), std::min(days_width, 10U), days, hours, minutes, seconds, milliseconds);
51 
52  return text.data();
53 }
54 
55 } // namespace log
56 
57 } // namespace uuid
Common utilities.
std::string format_timestamp_ms(uint64_t timestamp_ms, unsigned int days_width)
Format a system uptime timestamp as a string.