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.
To compile and run the program:
In this C program:
We use time() to get the current time in seconds since the Unix epoch.
For millisecond and nanosecond precision, we use gettimeofday(), which provides microsecond precision. We then calculate milliseconds and nanoseconds from this.
To convert seconds back to a readable time format, we use localtime() and strftime().
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.