Next, let's write Date Time Test2 and see how many
seconds it has been since January 1, 1970:
int main()
{
time_t myTime; // define a time_t variable
time(&myTime); // use as a pointer to get the
// time in seconds
printf("It has been %ld seconds since Jan. 1
1970\n",myTime);
return 0;
}
■ FIGURE 5. Seconds since epoch began.
Good grief, has it really been that long? It's
1,335,989,666 seconds already and it seems like only
yesterday (which is me being sarcastic about how useful
that number is to tell when now is). So, what is the date
and time that this number represents? Well, let's use the
asctime() function in Date Time3 to get the date and time
in a format that makes sense:
int main()
{
time_t myTime; // define a time_t variable
time(&myTime); // use as a pointer to get
// the time in seconds
printf("The current time is
%s.\n",asctime(localtime(&myTime)));
return 0;
}
■ FIGURE 6. Date Time Test3.
We used the localtime function to convert the time
since the beginning of the previously mentioned epoch
into a calendar time, and then used the asctime() function
to convert that into a string that we can then show on our
console window using the printf function.
SMILEY’S WORKSHOP
Next, let's write Date Time Test4 to get the epoch time,
and then convert that into the tm data structure so that
we can manipulate each aspect of the date and time as
separate variables:
int main()
{
time_t myTime; // define a time_t variable
time(&myTime); // use as a pointer to get
// the time in seconds
// load a pointer to a tm struct with the
// local time
struct tm* time_parts = localtime(&myTime);
printf("Let's look at the data:\n");
printf("tm_sec = %d\n",time_parts->tm_sec);
printf("tm_min = %d\n",time_parts->tm_min);
printf("tm_hour = %d\n",time_parts->tm_hour);
printf("tm_mday = %d\n",time_parts->tm_mday);
printf("tm_mon = %d\n",time_parts->tm_mon);
printf("tm_year = %d\n",time_parts->tm_year);
printf("tm_wday = %d\n",time_parts->tm_wday);
printf("tm_yday = %d\n",time_parts->tm_yday);
printf("tm_isdst =
%d\n",time_parts->tm_isdst);
return(0);
}
■ FIGURE 7. Show the tm structure.
Wait a second. The year is 112? Well, I neglected to
mention that the year is calculated by adding the value in
tm_year to the constant TM_YEAR_BASE that just happens
to be 1900. So, 1900 + 112 = 2012 and we are right on
time. You might notice that the month is 10, but in
Date Time3 we saw that it is November. What gives?
Well, months are 0 based, so January is 0 and
December is 11. We could take care of this in the
software, but it is good to reinforce what we are doing by
seeing the raw output.
You now have a good introduction to how C handles
dates and times on a PC, so let's see how we do this on
the Arduino.
February 2013 61