Library contents

C++ std::strftime

Format the same calendar date as a four-digit year, two-digit month, and two-digit day.

A simple example

std::strftime

  1. Start with January 2, 2024
  2. Do this Format year/month/day
  3. Result 2024/01/02
The format places the four-digit year first and pads month and day to two digits.

Syntax

C++ syntax
std::strftime(label, sizeof label, "%Y/%m/%d", &date)
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Print a consistent date on a receipt

An office prints dates on receipts or billing records that may cross a month boundary. Use calendar-aware date handling and a consistent representation so the displayed date can be read back unambiguously.

From the programdate.tm_year = 2024 - 1900
Result2024/02/29
lesson.cpp
#include <cstdio>
#include <ctime>

int main() {
    std::tm date {};
    date.tm_year = 2024 - 1900;
    date.tm_mon = 2 - 1;
    date.tm_mday = 29;
    char label[16];
    if (std::strftime(label, sizeof label, "%Y/%m/%d", &date) == 0) return 1;
    std::puts(label);
    return 0;
}
Output
2024/02/29

The date is February 29. Padding the month and day keeps the receipt layout consistent.

Advertisements

Name a concert recording

The school archive sorts dates in file names. Render the already validated date as year-month-day, using two digits for both month and day.

Given7 March 2026
Worked result2026-03-07

Label an exhibition proof

A printer needs a date stamp that sorts correctly in a list. Render the already validated date as year-month-day, using two digits for both month and day.

Given2 November 2027
Worked result2027-11-02

What to watch for

Formatting changes only the displayed text. Keep a date value for later calculations.

Documentation for std::strftime