Seconds to time

I have found some code in the forum to convert from seconds to time. I make a function from it. But it will not compile.

  1. Why can't I return hrMinSec? What to change? I want to get the string out of the function.
  2. Does the sec %= 60 format the seconds with two characters?
char secondsToHMS(unsigned int seconds, const char ms){
  unsigned int tme=0;
  if(ms == 'j'){                          // If value is millis (milliseconds)
    tme = seconds / 1000;
  } else {
    tme = seconds;
  }
  int hr = tme/3600;                          //Number of seconds in an hour
  int mins = (tme-hr*3600)/60;              //Remove the number of hours and calculate the minutes.
  int sec = tme-hr*3600-mins*60;            //Remove the number of hours and minutes, leaving only seconds.
  sec %= 60;
  mins %= 60;
  hr %= 24;

  String hrMinSec = (String(hr) + ":" + String(mins) + ":" + String(sec));  //Converts to HH:MM:SS string. This can be returned to the calling function.
  Serial.print("String Time: ");Serial.println (hrMinSec);
  return hrMinSec;
}

This states that the function returns a single character, not a String.

If you take a look at the error message, you should see some statement to that effect.

I have already tried that but I get this fault:

Compilation error: cannot convert 'StringSumHelper' to 'char' in initialization

Can you guess what that means, based on my comment?

If you would post the entire code, or reduced complete sketch illustrating the problem, and any error message, there would be less guessing and a faster time to solving this.

Without seeing more, just making the return type of secondsToHMD be String instead of char would get you going.

a7

Ahhh I changed to function to be a String. Then it works.

What is the difference between char and String? Is char only one character?

1 Like

There is a vast difference between data type "char" and a String object, a fundamental aspect of the C/C++ programming language.

If you are using AVR based Arduinos (Uno, etc.), avoid using Strings, as they cause memory problems and program crashes.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.