I've been messing around with this for awhile and ran into multiple problems with memory corruption and the like because of how I implemented it in my sketch (using too many Strings etc). As a programmer who is not very familiar with C++ I often find myself trying to do things the way I would in Java or C# or Python and the result is I shoot myself in the foot.
So how best to satisfy this use case?
Simply put, I have multiple places in my code where I need to format the current date and time by the timezone. Sometimes I need it for printing out a debug statement, sometimes I use it to assign the value to my LCD display, etc. Point being I'd like to encapsulate that logic into a single function so how can I write an efficient and memory safe function to do that? Here's basically what I am doing:
void currentDT(){
 time_t utc, est;
 utc = now();
 est = usEastern.toLocal(utc);
 tmElements_t tm;
 breakTime(est, tm);
 char dt[15];
 sprintf(dt, "%02d-%02d-%02d %02d:%02d", tm.Month, tm.Day, (tm.Year+1970), tm.Hour, tm.Minute, tm.Second);
}
C allows you to do that. C++ aims the gun and pulls the trigger for you.
so how can I write an efficient and memory safe function to do that?
What you have is a good start. Instead of the function owning the array that sprintf() writes to, it should be passed to the function. Then, the caller can print the array, write it to an SD card, write it to an LCD, or just admire it from a distance.
currentDT() is a lousy name for a function to format the date and time in the current timezone.
PaulS:
C allows you to do that. C++ aims the gun and pulls the trigger for you.
I am growing to appreciate that...I currently have no toes left on my right foot
PaulS:
What you have is a good start. Instead of the function owning the array that sprintf() writes to, it should be passed to the function. Then, the caller can print the array, write it to an SD card, write it to an LCD, or just admire it from a distance.
hmmm my reply to your main comment was cut off. What I said was:
I did try it in a function that took a char [ ] but I either coded it incorrect or called it incorrectly because it caused my program to crash. Could you take a stab at modifying what I posted and how to call it so I can see where I went wrong?
With only a snippet of code, I can give only a snippet of an answer. dt[] will go out of scope when the function returns. It needs to be global, static or created by the caller.
KeithRB:
With only a snippet of code, I can give only a snippet of an answer. dt[] will go out of scope when the function returns. It needs to be global, static or created by the caller.
OK. take a look at this, this is a function I have anytime I want to display the current date & time on my LCD: