Skip to content

Instantly share code, notes, and snippets.

@icodeforlove
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icodeforlove/134fe2b934c724397cd3 to your computer and use it in GitHub Desktop.
Save icodeforlove/134fe2b934c724397cd3 to your computer and use it in GitHub Desktop.
easy way to get pretty times in c++
const char * niceTime(time_t targetTime, time_t now = time(0)) {
const char *periods[8] = {"second", "minute", "hour", "day", "week", "month", "year", "decade"};
float lengths[7] = {60.0, 60.0, 24.0, 7.0, 4.35, 12.0, 10};
int difference = now > targetTime ? now - targetTime : targetTime - now;
int i = 0;
for (; difference >= lengths[i] && i < 7; i++) {
difference /= lengths[i];
}
difference = round(difference);
std::string period = periods[i];
if (difference != 1) {
period += "s";
}
std::ostringstream result;
result << difference << " " << period;
return result.str().c_str();
}
// usage
niceTime(1404377294); // returns result based on current time
niceTime(1404377294, 1404376994); // returns result based on specific time, in this case "5 minutes"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment