FREEBIE: return formatted duration

Here's a gift for anyone that wants it...
Call the getPeriodString() function with a value in millisecs, it returns a formatted global c-string (periodString)
e.g. "20.6min"

char periodString[20];  // the return string for longest possible return
unsigned long timePeriod = 1234; // millisecs


The function automagically formats the output to include the correct units to scale with the input number.
NOTE - uses sprintf()


#define MS_PER_SEC		1000L
#define MS_PER_MIN		60000L
#define MS_PER_HOUR		3600000L

// ========================================================================
char* getPeriodString(unsigned long duration) {
	double myTemp;
  if (duration) {
    if (duration < MS_PER_SEC) {
      sprintf(periodString, "%umS", duration);
    } else if (duration < MS_PER_MIN) {
			myTemp = ((double)duration) / MS_PER_SEC;
      dtostrf(myTemp, 3, 1, temp); 
      sprintf(periodString, "%ssec", temp);
    } else if (duration < MS_PER_HOUR) {
			myTemp = ((double)duration) / MS_PER_MIN;
      dtostrf(myTemp, 3, 1, temp); 
      sprintf(periodString, "%smin", temp);
    } else {  // big numbers must be hours!
			myTemp = ((double)duration) / MS_PER_HOUR;
      dtostrf(myTemp, 3, 1, temp); 
      sprintf(periodString, "%shrs", temp);
  } else {
    sprintf(periodString, "none");
  return periodString;
// ========================================================================

It could be extended to pluralise the return string (I needed specific 3-char fields)

  • and I did write the opposite function to take a float number appended with ms/m/h , and return an unsigned long in milliseconds - but I'll let you figure that out for now !

Why not make 'periodString' a (static) variable in the function? Seems like a neater solution. And make it halve as large because that's all you ever need ("1111.1hrs" is the largest).

Or make the sting to use a reference in the call.

Yeah, I just wanted to post something, no warranty implied...

Feel free to tweak and post updates to feed the free software masses

Your defines should be UL not L