w3resource

C strftime() function

C strftime() function - Convert date and time to a string

Syntax:

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

The strftime() function shall place bytes into the array pointed to by str as controlled by the string pointed to by format. The format is a character string, beginning and ending in its initial shift state, if any. The format string consists of zero or more conversion specifications and ordinary characters.

The fields of the tm structure include:

tm_sec Seconds (0-61)
tm_min Minutes (0-59)
tm_hour Hours (0-23)
tm_mday Day of month (1-31)
tm_mon Month (0-11; January = 0)
tm_year Year (current year minus 1900)
tm_wday Day of week (0-6; Sunday = 0)
tm_yday Day of year (0-365; January 1 = 0)
tm_isdst Zero if daylight saving time is not in effect; positive if daylight
saving time is in effect; negative if the information is not available.

Parameters:

Name Description Required /Optional
str Output string. Required
maxsize Size of the strDest buffer, measured in characters (char or wchar_t). Required
format Format-control string. Required
timeptr tm data structure. Required

Return value from strftime()

  • If the total number of resulting bytes including the terminating null byte is not more than maxsize, these functions shall return the number of bytes placed into the array pointed to by s, not including the terminating NUL character.
  • Otherwise, 0 shall be returned and the contents of the array are unspecified.

Example: strftime() function

The following example shows the usage of strftime() function.

#include <stdio.h>
#include <time.h>
 
int main(void)
{
     char text[100];
     int rs;
     time_t temp;
     struct tm *timeptr;

     temp = time(NULL);
     timeptr = localtime(&temp);
     rs = strftime(text,sizeof(text),"Today is %A, %b %d.\nTime:  %r", timeptr);
     printf("%s\n",text);

     return 0;
}

Output:

Today is Tuesday, Dec 20.
Time:  02:26:53 PM

C Programming Code Editor:

Previous C Programming: C mktime()
Next C Programming: C time()



Follow us on Facebook and Twitter for latest update.