-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtimeutils.h
58 lines (50 loc) · 1.45 KB
/
timeutils.h
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
// SPDX-FileCopyrightText: 2013-2024 Technical University of Munich
//
// SPDX-License-Identifier: BSD-3-Clause
//
// SPDX-FileContributor: Sebastian Rettenberger
#ifndef UTILS_TIMEUTILS_H_
#define UTILS_TIMEUTILS_H_
#include <ctime>
#include <string>
/**
* A collection of useful utility functions
*/
namespace utils {
/**
* A collection of usefull time functions
*/
class TimeUtils {
public:
/**
* Formats a string using strftime
*
* Taken from
* http://stackoverflow.com/questions/7935483/c-function-to-format-time-t-as-stdstring-buffer-length
*
* @return A copy of formatString, with all %k replaced with the time
* information
*/
static auto timeAsString(const std::string& formatString, time_t time) -> std::string {
const struct tm* timeinfo = localtime(&time);
std::string buffer;
buffer.resize(formatString.size() * 2);
size_t len = strftime(buffer.data(), buffer.size(), formatString.c_str(), timeinfo);
while (len == 0) {
buffer.resize(buffer.size() * 2);
len = strftime(buffer.data(), buffer.size(), formatString.c_str(), timeinfo);
}
buffer.resize(len);
return buffer;
}
/**
* @copydoc timeAsString(const std::string&, time_t)
*
* Returns the formated time for the current time
*/
static auto timeAsString(const std::string& formatString) -> std::string {
return timeAsString(formatString, time(nullptr));
}
};
} // namespace utils
#endif // UTILS_TIMEUTILS_H_