For some reason I can't use the Time.h lib.

Can you guys tell me how to create a string from the datetime into a format like this:


Seems odd that I can't find any examples of this.

  • That's because they all just print it. Oct 30, 2014 at 2:28
  • What DateTime are you talking about? The type from RTClib? Of some other DateTime? Apr 30, 2019 at 19:55

3 Answers 3


Is that what you want, mate?

char buf1[20];
DateTime now = rtc.now(); 
//Updated now.day to now.date
sprintf(buf1, "%02d:%02d:%02d %02d/%02d/%02d",  now.hour(), now.minute(), now.second(), now.date(), now.month(), now.year()); 

Serial.print(F("Date/Time: "));
  • Great answer, except that now.day() does not exist – now.date() is correct. (I tried editing but SE requires edits to be at least 6 characters…)
    – Caesar
    Feb 4, 2021 at 12:08
  • thanks for edit bro. Dec 7, 2021 at 16:02

If by DateTime you are referring to RTClib's DateTime (this is something you have to clarify in your question), then you can call unixtime() method on your DateTime object. The returned value is regular Unix "epoch" time, which can be used as time_t value with functions from <time.h> (and it's <time.h>, not <Time.h>).

For example, you can use ctime to convert Unix time_t value to a C-string, although the format of that string is different from the one you requested

DateTime dt;
time_t t = dt.unixtime();

const char *str = ctime(&t);

On Arduino you also have ctime_r available to you as a reentrant version of ctime.

Or, if you need more flexibility with the format, you can use gmtime or localtime and then strftime, but this might be excessive, since struct tm generated by gmtime is in essence very similar to DateTime. You can simply use snprintf in a manner suggested in @şevket Karayılan's answer.

Nevertheless, note that strftime provides you with quite extensive formatting capabilities, which would take some effort to reimplement manually

DateTime dt;
time_t t = dt.unixtime();
struct tm *lt = localtime(&t);

char str[32];
strftime(str, sizeof str, "%Y.%m.%d:%H.%M.%S", lt); 

strftime(str, sizeof str, "%x %X", lt); 

strftime(str, sizeof str, "%F %T", lt); 

There's no built in function to do that, I'm afraid.

I suggest you create a method that will format the string like so. Something along the lines of:

void formatTime()
   string str = year() + "." + month() + "." + day() + ":" + hour() + "FILL IN THE REST";
  • 1
    What is string in this case? And the initializer expression is definitely not valid. Apr 30, 2019 at 21:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.