Course contentsShow
← C
Lesson 894 of 1,21912. The Standard LibraryFree lesson

Formatting time strings with `strftime`

Formatting time strings with strftime

What you'll learn: How to transform raw system time into human-friendly text using a flexible template system.

The problem with raw time

In C, the tm struct holds time in pieces (seconds, minutes, hours). While you could manually print these using printf, it is tedious to handle leading zeros, abbreviated month names, or local date formats. Instead of building strings by hand, we use strftime (short for "string format time"), which works much like printf but uses specific codes for dates.

How it works

Think of strftime as a label maker. You provide a blank tape (a char array), a template (the format string), and the data (the tm struct). The function then "stamps" the formatted date onto your tape.

The format uses placeholders starting with %:

  • %Y: 4-digit year (2023)
  • %m: Month (01-12)
  • %d: Day of the month (01-31)
  • %H: Hour in 24-hour format
  • %M: Minute (00-59)
  • %A: Full weekday name (Sunday)

The code in action

To use strftime, you need a buffer large enough to hold the resulting text. The function returns the number of characters written, or 0 if the buffer was too small.

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

int main() {
    time_t raw_time = time(NULL);
    struct tm *info = localtime(&raw_time);
    
    char buffer[80];

    // Template: "Monday, Jan 01, 2024 - 15:30"
    // %A = Day, %b = Short Month, %d = Day num, %Y = Year, %R = 24h Time
    strftime(buffer, sizeof(buffer), "%A, %b %d, %Y - %R", info);

    printf("Formatted date: %s\n", buffer);

    return 0;
}

Why use it?

The beauty of strftime is its flexibility. If you want to change your app’s date format from "MM/DD/YYYY" to "DD-MM-YYYY," you only change one string of text in your code. It also handles international standards automatically, ensuring that leading zeros (like 09:05) are placed correctly without extra if statements.

Key takeaway

Use strftime to convert struct tm data into readable strings using % placeholders for years, months, and days.