Formatting dates and times, so that single digits have leading zeros

Hello,

I'm using the real-time clock to log date and time. My code is:

  logfile.print(now.unixtime()); // seconds since 1/1/1970
  logfile.print(", ");
  logfile.print('"');
  logfile.print(now.year(), DEC);
  logfile.print("/");
  logfile.print(now.month(), DEC);
  logfile.print("/");
  logfile.print(now.day(), DEC);
  logfile.print(" ");
  logfile.print(now.hour(), DEC);
  logfile.print(":");
  logfile.print(now.minute(), DEC);
  logfile.print(":");
  logfile.print(now.second(), DEC);

Currently single digits show up as single digits, e.g., the month 5 (it's May) shows up as 5. I would like single digits to have leading zeros, so that May would show up as 05, 8 seconds shows up as 08, and so on. When I later read the log file, my program will be expecting two digits for each numerical field.

Can someone please suggest a simple way to output single-digit numerical values with a leading zero.

thanks, Bruce

Can someone please suggest a simple way to output single-digit numerical values with a leading zero.

if(now.month() < 10)
   logFile.print("0");
logFile.print(now.month());

is as simple as it gets.

If it's less than 10, print an extra zero. :slight_smile:

Ah, you beat me to it!

Thanks very much!! Gosh, that is simple. Good to know it.

Bruce

Or use sprintf and print all your values into a single buffer using "%02d:%02d:%02d" etc