C Date and Time
The header time.h gives a program the current date and time, ways to format it, and a clock to measure how long work takes.
The current time
time(NULL) returns the current time as a time_t: the number of seconds since 1 January 1970. localtime breaks it into a struct tm with fields for the year, month, day, hour and so on. strftime formats it as text.
#include <stdio.h>
#include <time.h>
int main(void) {
time_t now = time(NULL);
struct tm *t = localtime(&now);
char text[64];
strftime(text, sizeof text, "%Y-%m-%d %H:%M:%S", t);
printf("Now: %s\n", text);
printf("Year %d, month %d, day %d\n", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
return 0;
}Note the two classic traps in struct tm: tm_year counts from 1900, and tm_mon goes from 0 (January) to 11. The output changes every time you run it.
| strftime code | Meaning |
|---|---|
%Y | year, 4 digits |
%m, %d | month and day, 2 digits |
%H, %M, %S | hour (24-hour clock), minute, second |
%A, %B | weekday and month name |
Working with a fixed date
A struct tm can be filled in by hand. mktime completes it, for example by working out the weekday, and returns the matching time_t:
#include <stdio.h>
#include <time.h>
int main(void) {
struct tm d = {0};
d.tm_year = 2024 - 1900;
d.tm_mon = 0; // January
d.tm_mday = 26;
d.tm_hour = 12;
mktime(&d);
char text[64];
strftime(text, sizeof text, "%A, %d %B %Y", &d);
printf("%s\n", text);
return 0;
}Friday, 26 January 2024
The difference between two time_t values, from difftime, is a number of seconds, which makes it easy to count the days between two dates.
Measuring how long code takes
clock() returns the processor time used by the program. Divide the difference by CLOCKS_PER_SEC to get seconds:
#include <stdio.h>
#include <time.h>
int main(void) {
clock_t start = clock();
volatile long long sum = 0;
for (long long i = 0; i < 10000000; i++) sum += i;
double seconds = (double)(clock() - start) / CLOCKS_PER_SEC;
printf("Sum: %lld, took about %.3f s\n", sum, seconds);
return 0;
}volatile stops the compiler from removing a loop whose result looks unused, so the measurement is real.
Practice exercises
- Print today's date as
DD/MM/YYYY. - Work out which weekday your birthday falls on this year.
- Count the days between 1 January and today using
difftime. - Measure how long it takes to fill an array of a million numbers.