Epoch in C

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in C.

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

int main() {
    // Use time() to get elapsed time since the Unix epoch in seconds
    time_t now = time(NULL);
    printf("Current time: %s", ctime(&now));

    // Print seconds since epoch
    printf("Seconds since epoch: %ld\n", now);

    // To get milliseconds and nanoseconds, we need to use gettimeofday()
    struct timeval tv;
    gettimeofday(&tv, NULL);

    // Print milliseconds since epoch
    long long milliseconds = tv.tv_sec * 1000LL + tv.tv_usec / 1000;
    printf("Milliseconds since epoch: %lld\n", milliseconds);

    // Print nanoseconds since epoch
    long long nanoseconds = tv.tv_sec * 1000000000LL + tv.tv_usec * 1000;
    printf("Nanoseconds since epoch: %lld\n", nanoseconds);

    // Convert integer seconds or nanoseconds since the epoch into the corresponding time
    struct tm *tm_info = localtime(&now);
    char buffer[26];
    strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
    printf("Time from seconds: %s\n", buffer);

    // For nanosecond precision, we'd need to use a more advanced time library

    return 0;
}

To compile and run the program:

$ gcc epoch.c -o epoch
$ ./epoch
Current time: Wed May 17 12:34:56 2023
Seconds since epoch: 1684320896
Milliseconds since epoch: 1684320896123
Nanoseconds since epoch: 1684320896123456789
Time from seconds: 2023-05-17 12:34:56

In this C program:

  1. We use time() to get the current time in seconds since the Unix epoch.

  2. For millisecond and nanosecond precision, we use gettimeofday(), which provides microsecond precision. We then calculate milliseconds and nanoseconds from this.

  3. To convert seconds back to a readable time format, we use localtime() and strftime().

  4. C doesn’t have built-in functions for nanosecond-precision time conversion like Go does. For such precision, you would need to use a more advanced time library or implement the conversion yourself.

Note that the exact output will depend on your system time when you run the program.

Next, we’ll look at another time-related task: time parsing and formatting.