Last active
August 29, 2015 14:03
-
-
Save icodeforlove/134fe2b934c724397cd3 to your computer and use it in GitHub Desktop.
easy way to get pretty times in c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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