Generates a formatted time and date string #include <time.h> size_t strftime ( char * restrict s , size_t n , const char * restrict format , const struct tm * restrict timeptr ); The strftime( ) function converts date and time information from a struct tm object addressed by the last pointer argument into a character string, following a format specified by the string addressed by the pointer argument format. The strftime( ) function stores the resulting string in the buffer addressed by the first pointer argument, without exceeding the buffer length specified by the second argument, n. The locations that strftime( ) reads from and writes to using its restricted pointer parameters must not overlap. Typically, the struct tm object is obtained by calling localtime( ) or gmtime( ). For a description of this structure type, see mktime( ) in this chapter. The generation of the output string is governed by the format string. In this way, strftime( ) is similar to the functions in the printf( ) family. The format string consists of ordinary characters, which are copied to the output buffer unchanged, and conversion specifications, which direct strftime( ) to convert a data item from the struct tm object and include it in the output string. Conversion specification syntaxThe conversion specifications have the following syntax: %[modifier]specifier The modifier, if present, instructs strftime( ) to use an alternative, locale-specific conversion for the specified data item, and is either E, for locale-specific calendars and clocks, or O, for locale-specific numeric symbols. The E modifier can be prefixed to the specifiers c, C, x, X, y, and Y. The O modifier can be prefixed to the specifiers d, e, H, I, m, M, S, u, U, V, w, W, and Y. All of the conversion specifiers are listed, with the struct tm members they refer to, in Table 17-10. The replacement value for the conversion specifiers depend on the LC_TIME category of the current locale, which can be changed by the setlocale( ) function.
The strftime( ) function returns the length of the string written to the output buffer, not counting the terminating null character. If the output is longer than the argument n allows, strftime( ) returns 0, and the contents of the output buffer are undetermined. Exampletime_t now; struct tm *localnow; char hdr_date[999] = ""; time( &now ); localnow = localtime( &now ); if ( strftime( hdr_date, 78, "Date: %a, %d %b %Y %T %z", localnow ) ) puts( hdr_date ); else return -1; This code prints a date field in RFC 2822 style, such as this one: Date: Thu, 10 Mar 2005 13:44:18 +0100 See Alsoasctime( ), ctime( ), mktime( ), localtime( ), gmtime( ), wcsftime( ), snprintf( ), setlocale( ) |