typestar

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

  1. time_t counts seconds since the epoch.
  2. localtime returns a pointer to shared static storage.
  3. strftime is where the format string lives.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 2 in Time, step 5 of 14 in Systems programming.

← Previous Next →