-
Notifications
You must be signed in to change notification settings - Fork 0
/
human-readable-duration-format.cpp
41 lines (32 loc) · 1.15 KB
/
human-readable-duration-format.cpp
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
#include <string>
#include <map>
#include <vector>
#include <sstream>
std::string format_duration(int seconds) {
std::map<unsigned int, std::string, std::greater<unsigned int>> seconds_in {{31536000, "year"},
{86400, "day"},
{3600, "hour"},
{60, "minute"},
{1, "second"}};
if (seconds == 0) return "now";
std::vector<std::pair<int, std::string>> v;
for (const auto& [key, value] : seconds_in)
{
if (seconds >= key)
{
int amount = seconds / key;
v.push_back(std::make_pair(amount, value));
seconds -= amount * key;
}
};
std::stringstream ss;
for (size_t i = 0; i < v.size(); i++)
{
ss << v.at(i).first << " " << v.at(i).second;
if (v.at(i).first > 1) ss << 's';
if (i + 2 == v.size()) ss << " and ";
else if (i +1 == v.size()) continue;
else ss << ", ";
}
return ss.str();
}