2

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:

yyyy.MM.dd:hh.mm.ss
2014.10.29:07.12.33

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

  • That's because they all just print it. – Ignacio Vazquez-Abrams Oct 30 '14 at 2:28
  • What DateTime are you talking about? The type from RTClib? Of some other DateTime? – AnT Apr 30 at 19:55
2

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";
}
  • What is string in this case? And the initializer expression is definitely not valid. – AnT Apr 30 at 21:49
2

Is that what you want, mate?

char buf1[20];
DateTime now = rtc.now();
sprintf(buf1, "%02d:%02d:%02d %02d/%02d/%02d",  now.hour(), now.minute(), now.second(), now.day(), now.month(), now.year());
Serial.print(F("Date/Time: "));
Serial.println(buf1);
2

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);
Serial.println(str);

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); 
Serial.println(str);

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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