strftime() function in C/C++

CC++Server Side Programming

The function strftime() is used to format the time and date as a string. It is declared in “time.h” header file in C language. It returns the total number of characters copied to the string, if string fits in less than size characters otherwise, returns zero.

Here is the syntax of strftime() in C language,

size_t strftime(char *string, size_t size, const char *format, const struct tm *time_pointer)

Here,

string − Pointer to the destination array.

size − Maximum number of characters to be copied.

format − Some special format specifiers to represent the time in tm.

time_pointer − Pointer to tm structure that contains the calendar time structure.

Here is an example of strftime() in C language,

Example

 Live Demo

#include <stdio.h>
#include <time.h>
int main () {
   time_t tim;
   struct tm *detl;
   char buf[80];
   time( &tim );
   detl = localtime( &tim );
   strftime(buf, 20, "%x - %I:%M%p", detl);
   printf("Date & time after formatting : %s", buf );
   return(0);
}

Output

Date & time after formatting : 10/23/18 - 10:33AM

In the above program, three variables of multiple data types are declared. The function localtime() is storing the current date and time. The function strftime() is copying the string and formatting it in some special structure by using some special specifiers.

detl = localtime( &tim );
strftime(buf, 20, "%x - %I:%M%p", detl);
raja
Published on 06-Nov-2018 06:10:40
Advertisements