C programming time.h function - size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr)
The strftime() function is a part of the standard C library and is declared in the <time.h> header file. It is used to format a time value as a string according to a given format string. The resulting formatted string is stored in a buffer specified by the str argument.
The function signature is:
refer to:aeditfigi.comsize_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr);
The strftime() function takes four arguments:
stris a pointer to the buffer where the formatted string should be stored.maxsizeis the size of the buffer pointed to bystr.formatis a string that specifies the format of the resulting string, using a set of format specifiers that begin with the percent (%) character.timeptris a pointer to astruct tmthat contains the broken-down time representation.
The strftime() function returns the number of characters written to the buffer (not including the terminating null character), or zero if an error occurs.
Here is an example usage of strftime():
#include <stdio.h>
#include <time.h>
int main() {
time_t current_time;
struct tm *time_info;
char time_string[100];
// Get the current time
time(¤t_time);
// Convert the current time to a struct tm representation in the local time zone
time_info = localtime(¤t_time);
// Format the time as a string using strftime
strftime(time_string, sizeof(time_string), "The current time is %I:%M:%S %p on %A, %B %d, %Y.", time_info);
// Print the resulting string
printf("%s\n", time_string);
return 0;
}
In this example, the time() function is used to get the current time, and localtime() is used to convert the time to a struct tm representation in the local time zone. strftime() is then used to format the time as a string according to a specified format, which includes the current time in 12-hour format, the current date, and the day of the week. The resulting formatted string is stored in a buffer, which is then printed to the console.
Note that the strftime() function uses a set of format specifiers to specify the format of the resulting string. These format specifiers begin with the percent (%) character and are replaced with the corresponding value from the struct tm. Some common format specifiers include %Y for the year, %m for the month, %d for the day of the month, %H for the hour (24-hour clock), %I for the hour (12-hour clock), %M for the minute, %S for the second, %p for the AM/PM indicator, and %A and %B for the day of the week and month names, respectively.
