Easy Tutorial
❮ Cpp Dynamic Memory Cpp Pointer Operators ❯

C Library Function - strftime()

C Standard Library - <time.h>

Description

The C library function sizet strftime(char *str, sizet maxsize, const char *format, const struct tm *timeptr) formats the time represented by the structure timeptr according to the formatting rules defined in format and stores it in str.

Declaration

Below is the declaration for the strftime() function.

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

Parameters

Specifier Replaced by Example
%a Abbreviated weekday name Sun
%A Full weekday name Sunday
%b Abbreviated month name Mar
%B Full month name March
%c Date and time representation Sun Aug 19 02:56:02 2012
%d Day of the month (01-31) 19
%H Hour in 24-hour format (00-23) 14
%I Hour in 12-hour format (01-12) 05
%j Day of the year (001-366) 231
%m Month in decimal (01-12) 08
%M Minutes (00-59) 55
%p AM or PM name PM
%S Seconds (00-61) 02
%U Week number of the year, with the first Sunday as the first day of the first week (00-53) 33
%w Weekday in decimal, with Sunday as 0 (0-6) 4
%W Week number of the year, with the first Monday as the first day of the first week (00-53) 34
%x Date representation 08/19/12
%X Time representation 02:50:06
%y Year, last two digits (00-99) 01
%Y Year 2012
%Z Time zone name or abbreviation CDT
%% A % character %

Return Value

If the resulting C string is less than size characters long (including the null-terminating character), the total number of characters (excluding the null-terminating character) copied to str is returned; otherwise, zero is returned.

Example

The following example demonstrates the use of the strftime() function.

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

int main ()
{
   time_t rawtime;
   struct tm *info;
   char buffer[80];

   time( &rawtime );
   info = localtime( &rawtime );

   strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", info);
   printf("Formatted date & time : |%s|\n", buffer );

   return 0;
}
char buffer[80];

time(&rawtime);

info = localtime(&rawtime);

strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", info);
printf("Formatted date & time: |%s|\n", buffer);

return 0;
}

Let's compile and run the above program, which will produce the following result:

Formatted date & time: |2018-09-19 08:59:07|

C Standard Library - <time.h>

❮ Cpp Dynamic Memory Cpp Pointer Operators ❯