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:
Format Explanation %a Abbreviated weekday name (Sun, Mon, ...) %A Full weekday name (Sunday, Monday, ...) %b Abbreviated month name (Jan, Feb, ...) %B Full month name (January, February, ...) %c Complete day and time (Feb 15 14:45:01 2013) %d Day of the month (0-31) %H Hour on 24-hour clock (00-23) %I Hour on a 12-hour clock (01-12) %j Day of the year (001-366) %m Month (0-12) %M Minute (00-59) %p AM/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.%w Weekday (0-6) %W Week number (00-53)
The first Monday is the beginning of week 1.%x Complete date (Feb 15 2013) %X Complete time (14:45:01) %y Year without century (00-99) %Y Year with century (2013) %Z Time 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:
Advertisements