The strftime
function is defined in the time.h
header file. It serves to create and store a string in accordance with the given format. It uses the values of time stored in a given tm
struct.
Following is the syntax for the strftime
function:
str
: The pointer to the destination array to which we copy the formatted string.
max_size
: The maximum number of characters which can be copied into the destination array pointed to by str
.
format
: A string to specify the format and the statement in which to display the time. Following is a table of some of the most commonly used specifiers and what they represent:
Specifier | Represents |
---|---|
%a |
Abbreviated name of the weekday (Mon) |
%^a |
Abbreviated name of the weekday in all capitals (MON) |
%A |
Full name of weekday (Monday) |
%b |
Abbreviated name of month (Jan) |
%^b |
Abbreviated name of month name in all capitals (JAN) |
%B |
Full name of month (January) |
%c |
Date and time (Mon Jan 01 01:01:01 2021) |
%d |
Day of the month (01-31) |
%H |
Hour in 24h format (00-23) |
%I |
Hour in 12h format (00-11) |
%j |
Day of the year (000-365) |
%m |
Month of the year (01-12) |
%M |
Minute in an hour (00-59) |
%S |
Seconds in an hour (00-59) |
%w |
Weekday as a number (0-6) |
%x |
Condensed date (01/01/21) |
%y |
Last two digits of the year (00-99) |
%Y |
Complete year (2021) |
time_ptr
: An object of type tm
containing values of time broken down into separate units. Following is the declaration for the structure tm
:Elements | Represent |
---|---|
tm_sec |
Seconds passed in a minute |
tm_min |
Minutes passed in an hour |
tm_hour |
Hours passed in a day |
tm_mday |
Months passed in a year |
tm_mon |
Months passed in a year |
tm_wday |
Days passed in a week |
tm_yday |
Days passed in a year |
tm_year |
Years passed since 1900 |
tm_isdst |
Daylight saving hours |
Upon successful execution, strftime
returns the number of characters copied into the destination array, else it returns a zero upon encountering errors during execution.
In this example, we first create and populate a tm
object and a buffer of size 100. Finally, we feed both these to the strftime
function and the maximum size of the buffer and the format. The format we use here is [%x] {%H:%M}
, which is simply the condensed date enclosed by square brackets followed by the Hours and minutes, separated by a colon, and enclosed in curly braces:
#include<stdio.h>#include<time.h>int main(){// variable to give as parameterstruct tm mytm;// the destination array to give as parameterchar buff[100];// populating the tm objectmytm.tm_year = 2021 - 1900; // 2021mytm.tm_isdst = 0; // day light saving set to 0mytm.tm_mon = 1; // Januarymytm.tm_mday = 0; // Sunday// setting the time as 01:01:01mytm.tm_hour = 1;mytm.tm_min = 1;mytm.tm_sec = 1;// strftime puts the formatted string into buffstrftime(buff,100,"[%x] {%H:%M}", &mytm);//print out buffprintf(" This is the formatted string: %s\n", buff );return 0;}
Free Resources