Hello folks,
I'm wondering what would be the best way to (convert and) format date information into a string for output?
e.g. with the help of char str[11]
variable?
// format a date into a string with leading zeros (if needed) on nDay and nMonth.
void setup() {
int nDay = 8;
int nMonth = 4;
int nYear = 2025;
Serial.print("today is: ");
Serial.print(nDay);
Serial.print("-");
Serial.print(nMonth);
Serial.print("-");
Serial.print(nYear);
Serial.println();
// expected output: [today is 08-04-2025]
// I know, the code is not doing that. It's just for demonstration
}
void loop () {
;
}
Any ideas or suggestions?
Thanks in advance
// format a date into a string with leading zeros (if needed) on nDay and nMonth.
void setup()
{
Serial.begin(115200);
int nDay = 8;
int nMonth = 4;
int nYear = 2025;
char buffer[40]; //large enough to hold the output string
snprintf(buffer, sizeof(buffer), "today is: %02d-%02d-%04d", nDay, nMonth, nYear);
Serial.println(buffer);
}
void loop()
{
}
I will leave you to research how the formatting works
3 Likes
Can You define good, better and the best?
Not sure what you mean by 'best way'. There are all sorts of libraries, examples, tutorials about the programers nemisis, dates.
I would look in the Arduino.cc HERE then search like THIS
NOTICE: bottom right, 16 libraries found. It looks to me like 4 to 6 might be of interest to you.
If I really have to answer your question, my answer would be:
good: it's working w/o any errors
better: it's working w/o errors, memory- and time efficient
the best: no further improvement possible.
But someone else might have different criteria.
I'm answering just for the fun of it.
Sweet.
I see I still can learn a lot more about C++.
That's the solution for me.
Thanks.
Thanks for the tip.
IMHO, its' more about string formatting than dates and times.
Not sure what your point is, anytime someone mentions date/time, it's 99% of the time about formatting it.
I hope you found an answer in all the informative posts.