totn C Functions

C Language: strftime function
(Write Formatted Date and Time to String)

In the C Programming Language, the strftime function stores characters into the array pointed to by s based on the string pointed to by format.

Syntax

The syntax for the strftime function in the C Language is:

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

Parameters or Arguments

s
An array where the characters will be written.
maxsize
The number of characters (including the null character) to be stored.
format

The format string to apply which can be:

FormatExplanation
%aAbbreviated weekday name (Sun, Mon, ...)
%AFull weekday name (Sunday, Monday, ...)
%bAbbreviated month name (Jan, Feb, ...)
%BFull month name (January, February, ...)
%cComplete day and time (Feb 15 14:45:01 2013)
%dDay of the month (0-31)
%HHour on 24-hour clock (00-23)
%IHour on a 12-hour clock (01-12)
%jDay of the year (001-366)
%mMonth (0-12)
%MMinute (00-59)
%pAM/PM (AM or PM)
%S Second (00-61)
Allows for 2 extra leap seconds
%U Week number (00-53)
The first Sunday is the beginning of week 1.
%wWeekday (0-6)
%W Week number (00-53)
The first Monday is the beginning of week 1.
%xComplete date (Feb 15 2013)
%XComplete time (14:45:01)
%yYear without century (00-99)
%YYear with century (2013)
%ZTime zone name or abbreviation (EST)
%%%
timeptr
A pointer to a structure whose values will be replaced.

Returns

The strftime function returns the number of characters stored (not including the null character).

If the number of characters stored (including the null character) exceeds maxsize, the strftime function will return zero.

Required Header

In the C Language, the required header for the strftime function is:

#include <time.h>

Applies To

In the C Language, the strftime function can be used in the following versions:

  • ANSI/ISO 9899-1990

strftime Example

Let's look at an example to see how you would use the strftime function in a C program:

/* Example using strftime by TechOnTheNet.com */

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

int main(int argc, const char * argv[])
{
   char result[100];
   time_t t;

   /* Retrieve the current time */
   t = time(NULL);

   /* Output the current year into the result string */
   strftime(result, sizeof(result), "%Y", localtime(&t));

   /* Output a message with the current year to the user */
   printf("It is now the year %s at TechOnTheNet.com!\n", result);

   return 0;
}

When compiled and run, this application will output "It is now the year" followed by the current year and then "at TechOnTheNet.com!". When we ran the application in 2017, the output was the following:

It is now the year 2017 at TechOnTheNet.com!

Similar Functions

Other C functions that are similar to the strftime function: