Looping with time_t values

In C, the time_t variable type is associated with the Unix epoch, or the number of seconds ticked since midnight, January 1, 1970. It’s typically a long int value, though as a typedef declaration, its specific data type could change in the future. Still, as a long int, you can play with it like other integers in your code.

For example:

#include <stdio.h>
#include <time.h>

#define POSTDATE 1528527660

int main()
{
    time_t t;

    for(t=POSTDATE;t<POSTDATE+600;t+=60)
        printf("%s",ctime(&t));

    return(0);
}

The POSTDATE constant expression is set at Line 4, equal to June 16, 2018 midnight. The for loop at Line 10 uses time_t variable t to loop through that value to a time_t value 600 seconds in the future, stepping 60 seconds at a time. Yes, this is a valid loop in the C language; time_t is a data type just like char or int.

Here’s the sample run:

Sat Jun 16 00:01:00 2018
Sat Jun 16 00:02:00 2018
Sat Jun 16 00:03:00 2018
Sat Jun 16 00:04:00 2018
Sat Jun 16 00:05:00 2018
Sat Jun 16 00:06:00 2018
Sat Jun 16 00:07:00 2018
Sat Jun 16 00:08:00 2018
Sat Jun 16 00:09:00 2018
Sat Jun 16 00:10:00 2018

I used this type of loop in code I wrote recently. The time_t value was part of a data structure, so the loop would recreate data inputs given the time of day and display the results.

You can modify the loop to display intervals greater than 60 seconds. The following code does this task with only a few modifications:

#include <stdio.h>
#include <time.h>

#define POSTDATE 1529132400
#define DAY 86400

int main()
{
    time_t t;

    for(t=POSTDATE;t<POSTDATE+(DAY*10);t+=DAY)
        printf("%s",ctime(&t));

    return(0);
}

In this code, I’ve changed the POSTDATE constant expression to represent midnight, which involves subtracting 60 from the value in the original code. The DAY constant expression is set to 86400, the number of seconds in a day.

Sat Jun 16 00:00:00 2018
Sun Jun 17 00:00:00 2018
Mon Jun 18 00:00:00 2018
Tue Jun 19 00:00:00 2018
Wed Jun 20 00:00:00 2018
Thu Jun 21 00:00:00 2018
Fri Jun 22 00:00:00 2018
Sat Jun 23 00:00:00 2018
Sun Jun 24 00:00:00 2018
Mon Jun 25 00:00:00 2018

Remember, these time_t values are interpreted in the code as epoch values. You can also display the values directly with only one addition to the code:

printf("%ld: %s",t,ctime(&t));

And you get this output:

1529132400: Sat Jun 16 00:00:00 2018
1529218800: Sun Jun 17 00:00:00 2018
1529305200: Mon Jun 18 00:00:00 2018
1529391600: Tue Jun 19 00:00:00 2018
1529478000: Wed Jun 20 00:00:00 2018
1529564400: Thu Jun 21 00:00:00 2018
1529650800: Fri Jun 22 00:00:00 2018
1529737200: Sat Jun 23 00:00:00 2018
1529823600: Sun Jun 24 00:00:00 2018
1529910000: Mon Jun 25 00:00:00 2018

The bottom line, and what I took advantage of in my code, is to understand that a time_t value is still a data type, and you can use it beneficially as either an epoch value or straight-up integer, depending on the needs of your code.

Leave a Reply