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.
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It only takes a minute to sign up.
Sign up to join this communityFor 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.
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);
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: "));
Serial.println(buf1);
now.day()
does not exist – now.date()
is correct. (I tried editing but SE requires edits to be at least 6 characters…)
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";
}
string
in this case? And the initializer expression is definitely not valid.
Apr 30, 2019 at 21:49
DateTime
are you talking about? The type from RTClib? Of some otherDateTime
?