First, if your display supports char array, as sterretje suggested, get rid of the String class. It eats memory more than it needs to and it can fragment it as well. Second, sprintf() is a powerful function, but rarely does one program use all of that power. As a result, it, too, chews up a lot of resources. The code suggested earlier with the String class and sprintf() uses 4888 bytes in the code below, if the appropriate lines are uncommented/commented. The revised code, even though I added a new function, is only 2522 bytes but has similar functionality.
#define DATE 1
#define TIME 2
void setup() {
// put your setup code here, to run once:
char timeStamp[12] = {0};
char dateStamp[11] = {0};
int displayHour = 12;
int minute = 22;
int sec = 33;
Serial.begin(9600);
DTFormatter(timeStamp, displayHour, minute, sec, TIME);
DTFormatter(dateStamp, 5, 3, 2015, DATE); // Replace with now() calls...
Serial.println(timeStamp);
Serial.println(dateStamp);
// sprintf(timeStamp, "%02d:%02d:%02d-%02s", displayHour, minute, sec, meridian);
// sprintf(dateStamp, "%02d/%02d/%04d", 5, 3, 2016);
// String ts;
// String ds;
// ts = timeStamp;
// ds = dateStamp;
// Serial.println(ts);
// Serial.println(ds);
}
/*****
Purpose: To format time and dates into a string
Parameter list:
char *result where the resulting result is stored
int hm a dual-function integer that holds either the 'h'our or 'm'month
int md 'm'inutes or 'd'ay
int sy 's'econds or 'y'ear
int which 1 = date, 2 = time
Return value:
void
*/
void DTFormatter(char *result, int hm, int md, int sy, int which)
{
char meridian[] = {" AM PM"};
char temp[5];
if (hm < 10) { // Do hour or month
strcpy(result, "0");
}
strcat(result, itoa(hm, temp, 10));
strcat(result, which == DATE?"/":":");
if (md < 10) { // Do minutes or days
strcat(result, "0");
}
strcat(result, itoa(md, temp, 10));
strcat(result, which == DATE?"/":":");
switch (which) {
case TIME:
strcat(result, itoa(sy, temp, 10));
if (hm >= 12) {
strncat(result, &meridian[3], 3);
} else {
strncat(result, meridian, 3);
}
break;
case DATE:
if (sy < 2000) // Only works for this century, although you'd expect 4 digits otherwise
sy += 2000;
strcat(result, itoa(sy, temp, 10));
break;
default:
strcpy(result, "Error");
break;
}
if (sy < 10) { // Do minutes or days
strcpy(result, "0");
}
}
void loop() {
}
There are probably some tweaks that could be made to the formatting function, too.
Edit: I forgot to remove the meridian array in setup().