Time and formatting in C
time gives seconds, localtime breaks them apart, strftime formats them.
#include <stdio.h>
#include <time.h>
void stamp(void) {
time_t now = time(NULL);
struct tm *local = localtime(&now);
char buffer[64];
strftime(buffer, sizeof buffer, "%Y-%m-%d %H:%M:%S", local);
printf("%s\n", buffer);
printf("day %d of year %d\n", local->tm_yday + 1,
local->tm_year + 1900);
}
double seconds_since(time_t past) {
return difftime(time(NULL), past);
}
How it works
time_tcounts seconds since the epoch.localtimereturns a pointer to shared static storage.strftimeis where the format string lives.
Keywords and builtins used here
NULLchardoublereturnseconds_sincesizeofstampstructtime_ttmvoid
The run, in numbers
- Lines
- 18
- Characters to type
- 371
- Tokens
- 103
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 62 seconds.
Step 1 of 2 in Time, step 5 of 14 in Systems programming.