strftime() function in C++

In this guide, you will learn what is strftime() function is in C++ programming and how to use it with an example.

1. strftime() Function Overview

The strftime() function in C++ is used to format the time represented by a tm structure into a character string. The function allows you to specify the desired format through format specifiers, enabling customization of the output string based on date and time components. This function is part of the <ctime> header.


size_t strftime(char* str, size_t count, const char* format, const struct tm* timeptr);


- str: Pointer to the destination buffer where the formatted string will be stored.

- count: Maximum number of characters to be written, including the null-terminator.

- format: Pointer to a character string containing the desired format.

- timeptr: Pointer to the tm structure containing the time information.

2. Source Code Example

#include <iostream>
#include <ctime>

int main() {
    std::time_t t;
    struct tm* local_time = localtime(&t);

    char buffer[100];
    strftime(buffer, sizeof(buffer), "Today is %A, %B %d, %Y", local_time);

    std::cout << buffer << std::endl;

    return 0;


Today is Dayname, Monthname dd, yyyy  (e.g., "Today is Tuesday, August 29, 2023")

3. Explanation

1. The current time is captured using the time() function and stored in a time_t variable.

2. The localtime() function is then employed to convert this time_t value into a tm structure representing local time.

3. The strftime() function is utilized to format the time according to the specified format. In this example, %A represents the full weekday name, %B denotes the full month name, %d is the day of the month, and %Y indicates the year.

4. The formatted string is then printed to the console.