strftime() - Time Date Function

How to convert time to string in C++?


strftime() converts the time and date, other information into the string pointed by "str", according to the format specified in "fmt". The function returns less than maxsize characters including the terminating null-character or returns zero if the contents of the array are indeterminate.


size_t strftime( char *str, size_t maxsize, const char *fmt,
const struct tm *time);

The following table lists the format specifiers used with this function.
Command Description
%a Abbreviated weekday name
%A Full weekday name
%b Abbreviated month name
%B Full month name
%c Date and time representation
%d Day of the month (01-31)
%H Hour in 24h format (00-23)
%I Hour in 12h format (01-12)
%j Day of the year (001-366)
%m Month as a decimal number (01-12)
%M Minute (00-59)
%p AM or PM designation
%S Second (00-61)
%U Week number with the first Sunday as the first day of week one (00-53)
%w Weekday as a decimal number with Sunday as 0 (0-6)
%W Week number with the first Monday as the first day of week one (00-53)
%x Date representation
%X Time representation
%y Year, last two digits (00-99)
%Y Year
%Z Timezone name or abbreviation
%% A % sign

Example :

#include <stdio.h>
#include <time.h>
int main ()
time_t t;
struct tm * ptr;
char buf [20];
time ( &t );
ptr= localtime ( &t );
strftime (buf,20,"This year is:: %Y",ptr);
puts (buf);
return 0;

Result :

This year is:: 2010

In the above example, "strftime()" is used with the format specifier "%Y" to get the converted string value of the current year .

C++ Tutorial

Ask Questions

Ask Question