strftime Function

Formats the time structure to a string based on the format parameter.

Include

<time.h>

Prototype

size_t strftime(char *s, size_t n, const char *format, const struct tm *tptr);

Arguments

s
output string
n
maximum length of string
format
format-control string
tptr
pointer to tm data structure

Return Value

Returns the number of characters placed in the array, s, if the total, including the terminating null, is not greater than n. Otherwise, the function returns 0 and the contents of array s are indeterminate.

Remarks

The format parameters follow:

%a abbreviated weekday name
%A full weekday name
%b abbreviated month name
%B full month name
%c appropriate date and time representation
%d day of the month (01-31)
%H hour of the day (00-23)
%I hour of the day (01-12)
%j day of the year (001-366)
%m month of the year (01-12)
%M minute of the hour (00-59)
%p AM/PM designator
%S second of the minute (00-61) allowing for up to two leap seconds
%U week number of the year where Sunday is the first day of week 1 (00-53)
%w weekday where Sunday is day 0 (0-6)
%W week number of the year where Monday is the first day of week 1 (00-53)
%x appropriate date representation
%X appropriate time representation
%y year without century (00-99)
%Y year with century
%Z time zone (possibly abbreviated) or no characters if time zone is unavailable
%% percent character %

Example

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

int main(void)
{
  time_t timer, whattime;
  struct tm *newtime;
  char buf[128];
  timer = 1066668182; /* Mon Oct 20 16:43:02 2003 */
  /* localtime allocates space for structure */
  newtime = localtime(&timer);
  strftime(buf, 128, "It was a %A, %d days into the "
           "month of %B in the year %Y.\n", newtime);
  printf(buf);
  strftime(buf, 128, "It was %W weeks into the year "
           "or %j days into the year.\n", newtime);
  printf(buf);
}

Example Output

It was a Monday, 20 days into the month of October in the year 2003.
It was 42 weeks into the year or 293 days into the year.