strftime() Function Example in C Programming

In this source code example, we will see how to use the strftime() function in C programming with an example.

strftime() Function Overview

The strftime() function in C is used for formatting date and time in a customized way. It transforms the struct tm representation of time to a string based on format specifiers provided. The function resides within the time.h library. 

Key Points: - strftime() requires the time.h header. 

- The function formats the date and time based on user-specified patterns. 

- It operates on the struct tm representation of time. 

- Various format specifiers allow for different date and time components.

Source Code Example

#include <stdio.h>
#include <time.h>  // Required for strftime(), localtime() and time()

int main() {
    time_t current_time;
    struct tm *local_time;
    char buffer[100];  // Buffer to store the formatted time

    // Obtain the current calendar time
    current_time = time(NULL);
    local_time = localtime(&current_time);

    if (local_time == NULL) {
        printf("Failed to obtain local time.\n");
        return 1;
    }

    // Format the time into the buffer
    if (strftime(buffer, sizeof(buffer), "%A, %d %B %Y %H:%M:%S", local_time) == 0) {
        printf("Buffer size is small or an error occurred.\n");
        return 1;
    }

    // Display the formatted time
    printf("Formatted time: %s\n", buffer);

    return 0;
}

Output

Formatted time: Wednesday, 23 June 2023 17:48:05
(Note: The output will differ based on the current system time and local settings.)

Explanation

1. We begin by incorporating the requisite header files: stdio.h for input/output functions and time.h for strftime(), localtime(), and time().

2. Inside the main() function, use time() to capture the current calendar time.

3. Convert the time_t value to its struct tm representation using localtime().

4. Then, use strftime() to format the struct tm data into a user-friendly string representation, leveraging format specifiers.

5. Ensure the process is successful by checking the return values of functions like localtime() and strftime().

6. Display the resulting formatted string.

The real power of strftime() lies in its format specifiers. These can be used to represent various parts of date and time, allowing for diverse and localized date-time formats. Familiarizing oneself with these specifiers unlocks the full potential of this function.


Comments