Skip to content

Instantly share code, notes, and snippets.

@AndiSHFR
Last active May 3, 2019 13:15
Show Gist options
  • Save AndiSHFR/c10173dbb88be6b84702 to your computer and use it in GitHub Desktop.
Save AndiSHFR/c10173dbb88be6b84702 to your computer and use it in GitHub Desktop.
Converts a duration in seconds into a human readable string.
/**
* HumanReadableDuration
*
* Retruns a human readable duration for totalSeconds.
* Make sure outputBuffer is big enough to hold the
* complete string incl. temrinate '\0' character.
*/
char* HumanReadableDuration(unsigned long totalSeconds, char* outputBuffer ) {
if(outputBuffer) {
char *workPos = outputBuffer;
// Calculate the uptime in hors, minutes and seconds
int uptimeDays = (int) (totalSeconds / (60 * 60 * 24L));
int uptimeHours = (int) ((totalSeconds / (60*60)) % 24);
int uptimeMinutes = (int) ((totalSeconds / 60) % 60);
int uptimeSeconds = (int) (totalSeconds % 60);
if(uptimeDays > 0) {
*workPos++ = '[';
if(uptimeDays > 9999) {
*workPos++ = (uptimeDays / 10000) + '0';
uptimeDays -= 10000;
}
if(uptimeDays > 999) {
*workPos++ = (uptimeDays / 1000) + '0';
uptimeDays -= 1000;
}
if(uptimeDays > 99) {
*workPos++ = (uptimeDays / 100) + '0';
uptimeDays -= 100;
}
if(uptimeDays > 9) *workPos++ = (uptimeDays / 10) + '0';
*workPos++ = (uptimeDays % 10) + '0';
*workPos++ = ']';
*workPos++ = ' ';
}
*workPos++ = (uptimeHours / 10) + '0';
*workPos++ = (uptimeHours % 10) + '0';
*workPos++ = ':';
*workPos++ = (uptimeMinutes / 10) + '0';
*workPos++ = (uptimeMinutes % 10) + '0';
*workPos++ = ':';
*workPos++ = (uptimeSeconds / 10) + '0';
*workPos++ = (uptimeSeconds % 10) + '0';
*workPos = 0;
}
return outputBuffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment