Time After Time

While writing some code recently, it became necessary to translate timestamp strings into time_t or epoch time values. This value is the number of seconds that have ticked since midnight, January 1, 1970. time_t values are stored long integers (generally), but I needed a utility to translate them into time strings. It turned out, such a tool wasn’t that difficult to create.

Here is the code I wrote for a utility I call epoch. It takes a command line time_t value or, if not present, it prompts for one. The value is output as a time string.

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

int main(int argc, char *argv[])
{
    time_t now;

    /* gather input */
    if(argc > 1)
    {
        now = atoi(argv[1]);
    }
    else
    {
        printf("Unix epoch time: ");
        scanf("%ld",&now);
    }

    printf("%s",ctime(&now));

    return(0);
}

The code turned out to be much simpler than I thought: time_t variable now is declared at Line 7. If argv[1] is present, it’s translated from a string into an int value by the atoi() function at Line 12. Otherwise, input is fetched at Line 17.

Yes, I used scanf() because it’s easy. And though a bogus value could be read, no potential for damage is made to the system by entering a bogus time_t value; you just get bad output.

The workhorse of the utility is the ctime() function in the printf() statement at Line 20, which outputs a time string.

Here’s a sample run:

./epoch 1528527600
Sat Jun  9 00:00:00 2018

The problem with the epoch utility is that it doesn’t do you any good unless you know a time_t value. You can guess at values, which is an interesting diversion, but instead of guessing, I wrote the now utility. It generates the time_t value for “right now.”

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

int main()
{
        time_t now;

        time(&now);
        printf("%ld\n",now);

        return(0);
}

This code declares the time_t variable now at Line 6, then fills that value by using the time() function at Line 8. The value, a long int, is printed at Line 9. Simple enough, as is the output:

./now
1528527600

And, if you’re using a Unix shell, you can combine the two commands to output the current time:

./epoch `./now`
Sat Jun  9 00:00:00 2018

Indeed, this code is silly stuff. Many utilities are silly, but their purpose greatly makes sense when you need them. In my case, I was working with time_t values and needed a quick way to translate them. These two utilities, epoch and now, proved most helpful.

Leave a Reply