You could also do this.
I had made a calendar class for my TFT_Extras library (TFT_Clocks to be exact). And all I did here was just copy that code then modify it to have AM or PM.
You also might be able to find a smaller code elsewhere online or within the forum.
unsigned long oldTime = millis();
int days_in_month[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const char *months[] = { "ERR", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
char Date[30]; // string buffer
unsigned int Cy; // years
byte Cm; // months
byte Cd; // days
unsigned long clock = 0; // variable to keep track of time in seconds
#define PM false
#define AM true
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
SetDate(1,1,2015); // January 1, 2015
SetTime(11, 59, 50, AM); // ...
}
void loop()
{
static byte s, m, h, ampm;
if (millis() - oldTime >= 1000) // update every second
{
oldTime += 1000;
s = clock % 60; // extract seconds from clock variable
m = (clock / 60) % 60; // extract minutes
h = clock / 3600; // extract hours
if (h == 0) // check for flip
h = 12;
if (h > 12) // military time converter
h -= 12;
// possibly overkill with sprintf()
sprintf(Date, "%s/%02d/%d %02d:%02d:%02d %s", months[Cm], Cd, Cy, h, m, s, (clock > 43199 ? "PM" : "AM"));
Serial.println(Date); // show the date + time
clock++; // increment clock
}
if (clock >= 86400) // Next day?
{
Calendar( &Cy, &Cm, &Cd); // day increments every time this function is called
clock = 0; // reset time
}
}
void Calendar( unsigned int *Y, byte *M, byte *D)
{
if (*D < (days_in_month[*M] + Leapyear(*M, *Y)) )
*D += 1;
else
{
*D = 1;
if (*M < 12)
*M += 1;
else
{
*M = 1;
*Y += 1;
}
}
} //End of Calendar Funct
byte Leapyear(byte month, unsigned long year) // gotten from online
{
if (month == 2) // February?
return ( ( (((year) % 4) == 0) && (((year) % 100) != 0) ) || (((year) % 400) == 0) );
return 0;
}
void SetTime(unsigned long hours, unsigned long minutes, unsigned long seconds, bool am_pm)
{
// This handles invalid time overflow ie 1(H), 0(M), 120(S) -> 1h, 2m, 0s
unsigned int S = (seconds / 60), M = (minutes / 60), H;
if (hours == 0)
H = 12;
if (hours > 12)
H = hours - 12;
if (S)
minutes += S;
if (M)
hours += M;
clock = (hours * 3600) + (minutes * 60) + (seconds % 60);
if ((hours > 12) || am_pm == false) // if AM = true, PM = false
clock += 43200;
}
void SetDate(byte m, byte d, int y)
{
Cm = m;
Cd = d;
Cy = y;
}