Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save lilyball/3856439 to your computer and use it in GitHub Desktop.

Select an option

Save lilyball/3856439 to your computer and use it in GitHub Desktop.
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
std::string human_readable_duration(int num_seconds) {
static int divisions[3] = {60, 60, 24};
std::stringstream buf;
if (num_seconds < divisions[0]) {
buf << num_seconds << " seconds";
} else {
std::vector<int> components;
for (int d = 0; d < sizeof(divisions)/sizeof(divisions[0]) && num_seconds > 0; num_seconds /= divisions[d++]) {
int comp = num_seconds % divisions[d];
components.push_back(comp);
}
if (num_seconds > 0) components.push_back(num_seconds);
std::vector<int>::const_reverse_iterator iter = components.rbegin();
buf << *(iter++);
for (; iter != components.rend(); ++iter) {
buf << ":" << std::setw(2) << std::setfill('0') << *iter;
}
}
return buf.str();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment