ptg10805159
194 System Data Files and Information Chapter 6
containing the first day in January has four or moredays in the new year,then this is
treated as week 1. Otherwise, it is treated as the last week of the previous year.Inboth
cases, Monday is treated as the first day of the week.
As with printf, strftime supports modifiers for some of the conversion
specifiers. TheEandOmodifiers can be used to generate an alternative format if one is
supported by the locale.
Some systems support additional, nonstandardextensions to theformatstring forstrftime.
Example
Figure6.11shows how to use several of the time functions discussed in this chapter.In
particular, it shows howstrftimecan be used to print a string containing the current
date and time.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int
main(void)
{
time_t t;
struct tm *tmp;
char buf1[16];
char buf2[64];
time(&t);
tmp = localtime(&t);
if (strftime(buf1, 16, "time and date: %r, %a %b %d, %Y", tmp) == 0)
printf("buffer length 16 is too small\n");
else
printf("%s\n", buf1);
if (strftime(buf2, 64, "time and date: %r, %a %b %d, %Y", tmp) == 0)
printf("buffer length 64 is too small\n");
else
printf("%s\n", buf2);
exit(0);
}
Figure 6.11 Using thestrftimefunction
Recall the relationship of the various time functions shown in Figure6.9. Before we can
print the time in a human-readable format, we need to get the time and convert it into a
broken-down time structure. Sample output from Figure6.11is
$./a.out
buffer length 16 is too small
time and date: 11:12:35 PM, Thu Jan 19, 2012