Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Formatting Date and Time in C Using strftime

Tech May 8 5

The strftime() function in the C standard library is a powerful tool for converting time and date information into a human-readable string based on specific formatting rules. It provides a highly flexible way to represent calendar time stored in a struct tm object.

Function Signature

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

Parameter Details

  • str: A pointer to the destination character aray where the resulting formatted string will be stored.
  • maxsize: The maximum number of characters to be written to the buffer, including the null terminator.
  • format: A C string containing plain characters and special format specifiers. Thece specifiers begin with a % sign and are replaced by the function with corresponding time values.
  • timeptr: A pointer to a tm structure that contains the broken-down time components.

Format Specifiers

Specifier Description Example
%a Abbreviated day of the week Mon
%A Full day of the week Monday
%b Abbreviated month name Jan
%B Full month name January
%c Standard date and time string Mon Jan 01 12:00:00 2024
%d Day of the month (01-31) 15
%H Hour in 24-hour format (00-23) 22
%I Hour in 12-hour format (01-12) 10
%j Day of the year (001-366) 045
%m Month as a decimal number (01-12) 05
%M Minute (00-59) 30
%p AM or PM designation PM
%S Second (00-61) 05
%U Week number (Sunday as first day) 02
%w Weekday as a decimal (Sunday = 0) 1
%W Week number (Monday as first day) 02
%x Date representation 05/15/24
%X Time representation 22:30:05
%y Year without century (00-99) 24
%Y Full year 2024
%Z Time zone name or abbreviation UTC
%% A literal percent sign %

The struct tm Definition

The timeptr argument refers to the following structure defined in <time.h>:

struct tm {
   int tm_sec;   // Seconds (0-59)
   int tm_min;   // Minutes (0-59)
   int tm_hour;  // Hours (0-23)
   int tm_mday;  // Day of the month (1-31)
   int tm_mon;   // Month (0-11)
   int tm_year;  // Years since 1900
   int tm_wday;  // Day of the week (0-6, Sunday = 0)
   int tm_yday;  // Day of the year (0-365)
   int tm_isdst; // Daylight Saving Time flag
};

Return Value

If the resulting string fits within the buffer (including the null terminator), the function returns the number of characters written. If the string exceeds the provided maxsize, the function returns 0, and the content of the buffer is undefined.

Practical Implementation

The following example demonstrates how to retrieve the current system time and format it into a custom string.

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

int main() {
    time_t timestamp;
    struct tm *datetime_info;
    char result_buffer[100];

    // Capture the current system time
    time(&timestamp);

    // Convert to local time structure
    datetime_info = localtime(&timestamp);

    // Format time: YYYY-MM-DD HH:MM:SS
    size_t written = strftime(result_buffer, sizeof(result_buffer), "%Y-%m-%d %H:%M:%S", datetime_info);

    if (written != 0) {
        printf("Formatted Timestamp: %s\n", result_buffer);
    } else {
        printf("Buffer size is too small for the format string.\n");
    }

    // Another format: Day, Month Date, Year
    strftime(result_buffer, sizeof(result_buffer), "%A, %B %d, %Y", datetime_info);
    printf("Human Readable: %s\n", result_buffer);

    return 0;
}
Tags: cprogramming

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.