C Reference function strftime()

Usage of strftime():

size_t strftime ( char * ptr_dest, size_t maxsize, const char * format, const struct tm * ptr_time );

Parameters:

ptr_dest is a pointer to the destination array where the resulting C string is copied too.

The maxsize contains the maximum number of characters to be copied to ptr_dest.

ptr_time is a pointer to a tm structure that contains a calendar time.

Format contains a C string with any combination of regular characters and special format commands.
These format commands are replaced by the function to the corresponding values to represent the time specified in ptr_time.
They all begin with a percentage (%) sign. Take a look at the following table:

Command

Replaced by

An example

%a Abbreviated weekday name * Fri
%A Full weekday name * Friday
%b Abbreviated month name * Dec
%B Full month name * December
%c Date and time representation * Fri Jan 11 13:53:32
2008
%d Day of the month (01-31) 11
%H Hour in 24h format (00-23) 13
%I Hour in 12h format (01-12) 01
%j Day of the year (001-366) 011
%m Month as a decimal number (01-12) 01
%M Minute (00-59) 53
%p AM or PM AM
%S Second (00-61) 32
%U Week number with the first Sunday as the first day of week one (00-53) 11
%w Weekday as a decimal number with Sunday as 0 (0-6) 3
%W Week number with the first Monday as the first day of week one (00-53) 34
%x Date * 01/11/08
%X Time * 13:53:32
%y Year, last two digits (00-99) 08
%Y Year 2008
%Z Time zone name or abbreviation CDT
%% A %
sign
%

* Are locale-dependent.

Note: some compilers may contain additional commands.

Return Value:

If the resulting C string fits in less than maxsize characters (including the terminating null-character) the total
number of characters copied to ptr_dest (not including the terminating null-character) is returned.

If it doesn’t fit, then zero will be returned. If this happens then the contents of the array is on determinate.

Explanation:

Copies into ptr_dest the content of format, expanding its format tags into the corresponding values as
specified by ptr_time, with a limit of maxsize characters.

Source code example of strftime():


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

	int main ()
	{
		time_t time_raw_format;
		struct tm * time_struct;

		char buf [100];

		time ( &time_raw_format );
		time_struct = localtime ( &time_raw_format );

		strftime (buf,100,"It is now: %I:%M%p.",time_struct);
		puts (buf);

		return 0;
	}

Output example of the program above:


	It is now: 02:45PM.

This entry was posted in C Reference time.h Functions. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Tweet This! Tweet This! or use to share this post with others.

Leave a Reply: