]> sourceware.org Git - glibc.git/blob - manual/time.texi
Allow strptime read outputs from strftime. Fixes bug 4772.
[glibc.git] / manual / time.texi
1 @node Date and Time, Resource Usage And Limitation, Arithmetic, Top
2 @c %MENU% Functions for getting the date and time and formatting them nicely
3 @chapter Date and Time
4
5 This chapter describes functions for manipulating dates and times,
6 including functions for determining what time it is and conversion
7 between different time representations.
8
9 @menu
10 * Time Basics:: Concepts and definitions.
11 * Elapsed Time:: Data types to represent elapsed times
12 * Processor And CPU Time:: Time a program has spent executing.
13 * Calendar Time:: Manipulation of ``real'' dates and times.
14 * Setting an Alarm:: Sending a signal after a specified time.
15 * Sleeping:: Waiting for a period of time.
16 @end menu
17
18
19 @node Time Basics
20 @section Time Basics
21 @cindex time
22
23 Discussing time in a technical manual can be difficult because the word
24 ``time'' in English refers to lots of different things. In this manual,
25 we use a rigorous terminology to avoid confusion, and the only thing we
26 use the simple word ``time'' for is to talk about the abstract concept.
27
28 A @dfn{calendar time} is a point in the time continuum, for example
29 November 4, 1990 at 18:02.5 UTC. Sometimes this is called ``absolute
30 time''.
31 @cindex calendar time
32
33 We don't speak of a ``date'', because that is inherent in a calendar
34 time.
35 @cindex date
36
37 An @dfn{interval} is a contiguous part of the time continuum between two
38 calendar times, for example the hour between 9:00 and 10:00 on July 4,
39 1980.
40 @cindex interval
41
42 An @dfn{elapsed time} is the length of an interval, for example, 35
43 minutes. People sometimes sloppily use the word ``interval'' to refer
44 to the elapsed time of some interval.
45 @cindex elapsed time
46 @cindex time, elapsed
47
48 An @dfn{amount of time} is a sum of elapsed times, which need not be of
49 any specific intervals. For example, the amount of time it takes to
50 read a book might be 9 hours, independently of when and in how many
51 sittings it is read.
52
53 A @dfn{period} is the elapsed time of an interval between two events,
54 especially when they are part of a sequence of regularly repeating
55 events.
56 @cindex period of time
57
58 @dfn{CPU time} is like calendar time, except that it is based on the
59 subset of the time continuum when a particular process is actively
60 using a CPU. CPU time is, therefore, relative to a process.
61 @cindex CPU time
62
63 @dfn{Processor time} is an amount of time that a CPU is in use. In
64 fact, it's a basic system resource, since there's a limit to how much
65 can exist in any given interval (that limit is the elapsed time of the
66 interval times the number of CPUs in the processor). People often call
67 this CPU time, but we reserve the latter term in this manual for the
68 definition above.
69 @cindex processor time
70
71 @node Elapsed Time
72 @section Elapsed Time
73 @cindex elapsed time
74
75 One way to represent an elapsed time is with a simple arithmetic data
76 type, as with the following function to compute the elapsed time between
77 two calendar times. This function is declared in @file{time.h}.
78
79 @comment time.h
80 @comment ISO
81 @deftypefun double difftime (time_t @var{time1}, time_t @var{time0})
82 The @code{difftime} function returns the number of seconds of elapsed
83 time between calendar time @var{time1} and calendar time @var{time0}, as
84 a value of type @code{double}. The difference ignores leap seconds
85 unless leap second support is enabled.
86
87 In @theglibc{}, you can simply subtract @code{time_t} values. But on
88 other systems, the @code{time_t} data type might use some other encoding
89 where subtraction doesn't work directly.
90 @end deftypefun
91
92 @Theglibc{} provides two data types specifically for representing
93 an elapsed time. They are used by various @glibcadj{} functions, and
94 you can use them for your own purposes too. They're exactly the same
95 except that one has a resolution in microseconds, and the other, newer
96 one, is in nanoseconds.
97
98 @comment sys/time.h
99 @comment BSD
100 @deftp {Data Type} {struct timeval}
101 @cindex timeval
102 The @code{struct timeval} structure represents an elapsed time. It is
103 declared in @file{sys/time.h} and has the following members:
104
105 @table @code
106 @item long int tv_sec
107 This represents the number of whole seconds of elapsed time.
108
109 @item long int tv_usec
110 This is the rest of the elapsed time (a fraction of a second),
111 represented as the number of microseconds. It is always less than one
112 million.
113
114 @end table
115 @end deftp
116
117 @comment sys/time.h
118 @comment POSIX.1
119 @deftp {Data Type} {struct timespec}
120 @cindex timespec
121 The @code{struct timespec} structure represents an elapsed time. It is
122 declared in @file{time.h} and has the following members:
123
124 @table @code
125 @item long int tv_sec
126 This represents the number of whole seconds of elapsed time.
127
128 @item long int tv_nsec
129 This is the rest of the elapsed time (a fraction of a second),
130 represented as the number of nanoseconds. It is always less than one
131 billion.
132
133 @end table
134 @end deftp
135
136 It is often necessary to subtract two values of type @w{@code{struct
137 timeval}} or @w{@code{struct timespec}}. Here is the best way to do
138 this. It works even on some peculiar operating systems where the
139 @code{tv_sec} member has an unsigned type.
140
141 @smallexample
142 @include timeval_subtract.c.texi
143 @end smallexample
144
145 Common functions that use @code{struct timeval} are @code{gettimeofday}
146 and @code{settimeofday}.
147
148
149 There are no @glibcadj{} functions specifically oriented toward
150 dealing with elapsed times, but the calendar time, processor time, and
151 alarm and sleeping functions have a lot to do with them.
152
153
154 @node Processor And CPU Time
155 @section Processor And CPU Time
156
157 If you're trying to optimize your program or measure its efficiency,
158 it's very useful to know how much processor time it uses. For that,
159 calendar time and elapsed times are useless because a process may spend
160 time waiting for I/O or for other processes to use the CPU. However,
161 you can get the information with the functions in this section.
162
163 CPU time (@pxref{Time Basics}) is represented by the data type
164 @code{clock_t}, which is a number of @dfn{clock ticks}. It gives the
165 total amount of time a process has actively used a CPU since some
166 arbitrary event. On @gnusystems{}, that event is the creation of the
167 process. While arbitrary in general, the event is always the same event
168 for any particular process, so you can always measure how much time on
169 the CPU a particular computation takes by examining the process' CPU
170 time before and after the computation.
171 @cindex CPU time
172 @cindex clock ticks
173 @cindex ticks, clock
174
175 On @gnulinuxhurdsystems{}, @code{clock_t} is equivalent to @code{long int} and
176 @code{CLOCKS_PER_SEC} is an integer value. But in other systems, both
177 @code{clock_t} and the macro @code{CLOCKS_PER_SEC} can be either integer
178 or floating-point types. Casting CPU time values to @code{double}, as
179 in the example above, makes sure that operations such as arithmetic and
180 printing work properly and consistently no matter what the underlying
181 representation is.
182
183 Note that the clock can wrap around. On a 32bit system with
184 @code{CLOCKS_PER_SEC} set to one million this function will return the
185 same value approximately every 72 minutes.
186
187 For additional functions to examine a process' use of processor time,
188 and to control it, see @ref{Resource Usage And Limitation}.
189
190
191 @menu
192 * CPU Time:: The @code{clock} function.
193 * Processor Time:: The @code{times} function.
194 @end menu
195
196 @node CPU Time
197 @subsection CPU Time Inquiry
198
199 To get a process' CPU time, you can use the @code{clock} function. This
200 facility is declared in the header file @file{time.h}.
201 @pindex time.h
202
203 In typical usage, you call the @code{clock} function at the beginning
204 and end of the interval you want to time, subtract the values, and then
205 divide by @code{CLOCKS_PER_SEC} (the number of clock ticks per second)
206 to get processor time, like this:
207
208 @smallexample
209 @group
210 #include <time.h>
211
212 clock_t start, end;
213 double cpu_time_used;
214
215 start = clock();
216 @dots{} /* @r{Do the work.} */
217 end = clock();
218 cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
219 @end group
220 @end smallexample
221
222 Do not use a single CPU time as an amount of time; it doesn't work that
223 way. Either do a subtraction as shown above or query processor time
224 directly. @xref{Processor Time}.
225
226 Different computers and operating systems vary wildly in how they keep
227 track of CPU time. It's common for the internal processor clock
228 to have a resolution somewhere between a hundredth and millionth of a
229 second.
230
231 @comment time.h
232 @comment ISO
233 @deftypevr Macro int CLOCKS_PER_SEC
234 The value of this macro is the number of clock ticks per second measured
235 by the @code{clock} function. POSIX requires that this value be one
236 million independent of the actual resolution.
237 @end deftypevr
238
239 @comment time.h
240 @comment ISO
241 @deftp {Data Type} clock_t
242 This is the type of the value returned by the @code{clock} function.
243 Values of type @code{clock_t} are numbers of clock ticks.
244 @end deftp
245
246 @comment time.h
247 @comment ISO
248 @deftypefun clock_t clock (void)
249 This function returns the calling process' current CPU time. If the CPU
250 time is not available or cannot be represented, @code{clock} returns the
251 value @code{(clock_t)(-1)}.
252 @end deftypefun
253
254
255 @node Processor Time
256 @subsection Processor Time Inquiry
257
258 The @code{times} function returns information about a process'
259 consumption of processor time in a @w{@code{struct tms}} object, in
260 addition to the process' CPU time. @xref{Time Basics}. You should
261 include the header file @file{sys/times.h} to use this facility.
262 @cindex processor time
263 @cindex CPU time
264 @pindex sys/times.h
265
266 @comment sys/times.h
267 @comment POSIX.1
268 @deftp {Data Type} {struct tms}
269 The @code{tms} structure is used to return information about process
270 times. It contains at least the following members:
271
272 @table @code
273 @item clock_t tms_utime
274 This is the total processor time the calling process has used in
275 executing the instructions of its program.
276
277 @item clock_t tms_stime
278 This is the processor time the system has used on behalf of the calling
279 process.
280
281 @item clock_t tms_cutime
282 This is the sum of the @code{tms_utime} values and the @code{tms_cutime}
283 values of all terminated child processes of the calling process, whose
284 status has been reported to the parent process by @code{wait} or
285 @code{waitpid}; see @ref{Process Completion}. In other words, it
286 represents the total processor time used in executing the instructions
287 of all the terminated child processes of the calling process, excluding
288 child processes which have not yet been reported by @code{wait} or
289 @code{waitpid}.
290 @cindex child process
291
292 @item clock_t tms_cstime
293 This is similar to @code{tms_cutime}, but represents the total processor
294 time system has used on behalf of all the terminated child processes
295 of the calling process.
296 @end table
297
298 All of the times are given in numbers of clock ticks. Unlike CPU time,
299 these are the actual amounts of time; not relative to any event.
300 @xref{Creating a Process}.
301 @end deftp
302
303 @comment time.h
304 @comment POSIX.1
305 @deftypevr Macro int CLK_TCK
306 This is an obsolete name for the number of clock ticks per second. Use
307 @code{sysconf (_SC_CLK_TCK)} instead.
308 @end deftypevr
309
310 @comment sys/times.h
311 @comment POSIX.1
312 @deftypefun clock_t times (struct tms *@var{buffer})
313 The @code{times} function stores the processor time information for
314 the calling process in @var{buffer}.
315
316 The return value is the number of clock ticks since an arbitrary point
317 in the past, e.g. since system start-up. @code{times} returns
318 @code{(clock_t)(-1)} to indicate failure.
319 @end deftypefun
320
321 @strong{Portability Note:} The @code{clock} function described in
322 @ref{CPU Time} is specified by the @w{ISO C} standard. The
323 @code{times} function is a feature of POSIX.1. On @gnusystems{}, the
324 CPU time is defined to be equivalent to the sum of the @code{tms_utime}
325 and @code{tms_stime} fields returned by @code{times}.
326
327 @node Calendar Time
328 @section Calendar Time
329
330 This section describes facilities for keeping track of calendar time.
331 @xref{Time Basics}.
332
333 @Theglibc{} represents calendar time three ways:
334
335 @itemize @bullet
336 @item
337 @dfn{Simple time} (the @code{time_t} data type) is a compact
338 representation, typically giving the number of seconds of elapsed time
339 since some implementation-specific base time.
340 @cindex simple time
341
342 @item
343 There is also a "high-resolution time" representation. Like simple
344 time, this represents a calendar time as an elapsed time since a base
345 time, but instead of measuring in whole seconds, it uses a @code{struct
346 timeval} data type, which includes fractions of a second. Use this time
347 representation instead of simple time when you need greater precision.
348 @cindex high-resolution time
349
350 @item
351 @dfn{Local time} or @dfn{broken-down time} (the @code{struct tm} data
352 type) represents a calendar time as a set of components specifying the
353 year, month, and so on in the Gregorian calendar, for a specific time
354 zone. This calendar time representation is usually used only to
355 communicate with people.
356 @cindex local time
357 @cindex broken-down time
358 @cindex Gregorian calendar
359 @cindex calendar, Gregorian
360 @end itemize
361
362 @menu
363 * Simple Calendar Time:: Facilities for manipulating calendar time.
364 * High-Resolution Calendar:: A time representation with greater precision.
365 * Broken-down Time:: Facilities for manipulating local time.
366 * High Accuracy Clock:: Maintaining a high accuracy system clock.
367 * Formatting Calendar Time:: Converting times to strings.
368 * Parsing Date and Time:: Convert textual time and date information back
369 into broken-down time values.
370 * TZ Variable:: How users specify the time zone.
371 * Time Zone Functions:: Functions to examine or specify the time zone.
372 * Time Functions Example:: An example program showing use of some of
373 the time functions.
374 @end menu
375
376 @node Simple Calendar Time
377 @subsection Simple Calendar Time
378
379 This section describes the @code{time_t} data type for representing calendar
380 time as simple time, and the functions which operate on simple time objects.
381 These facilities are declared in the header file @file{time.h}.
382 @pindex time.h
383
384 @cindex epoch
385 @comment time.h
386 @comment ISO
387 @deftp {Data Type} time_t
388 This is the data type used to represent simple time. Sometimes, it also
389 represents an elapsed time. When interpreted as a calendar time value,
390 it represents the number of seconds elapsed since 00:00:00 on January 1,
391 1970, Coordinated Universal Time. (This calendar time is sometimes
392 referred to as the @dfn{epoch}.) POSIX requires that this count not
393 include leap seconds, but on some systems this count includes leap seconds
394 if you set @code{TZ} to certain values (@pxref{TZ Variable}).
395
396 Note that a simple time has no concept of local time zone. Calendar
397 Time @var{T} is the same instant in time regardless of where on the
398 globe the computer is.
399
400 In @theglibc{}, @code{time_t} is equivalent to @code{long int}.
401 In other systems, @code{time_t} might be either an integer or
402 floating-point type.
403 @end deftp
404
405 The function @code{difftime} tells you the elapsed time between two
406 simple calendar times, which is not always as easy to compute as just
407 subtracting. @xref{Elapsed Time}.
408
409 @comment time.h
410 @comment ISO
411 @deftypefun time_t time (time_t *@var{result})
412 The @code{time} function returns the current calendar time as a value of
413 type @code{time_t}. If the argument @var{result} is not a null pointer,
414 the calendar time value is also stored in @code{*@var{result}}. If the
415 current calendar time is not available, the value
416 @w{@code{(time_t)(-1)}} is returned.
417 @end deftypefun
418
419 @c The GNU C library implements stime() with a call to settimeofday() on
420 @c Linux.
421 @comment time.h
422 @comment SVID, XPG
423 @deftypefun int stime (const time_t *@var{newtime})
424 @code{stime} sets the system clock, i.e., it tells the system that the
425 current calendar time is @var{newtime}, where @code{newtime} is
426 interpreted as described in the above definition of @code{time_t}.
427
428 @code{settimeofday} is a newer function which sets the system clock to
429 better than one second precision. @code{settimeofday} is generally a
430 better choice than @code{stime}. @xref{High-Resolution Calendar}.
431
432 Only the superuser can set the system clock.
433
434 If the function succeeds, the return value is zero. Otherwise, it is
435 @code{-1} and @code{errno} is set accordingly:
436
437 @table @code
438 @item EPERM
439 The process is not superuser.
440 @end table
441 @end deftypefun
442
443
444
445 @node High-Resolution Calendar
446 @subsection High-Resolution Calendar
447
448 The @code{time_t} data type used to represent simple times has a
449 resolution of only one second. Some applications need more precision.
450
451 So, @theglibc{} also contains functions which are capable of
452 representing calendar times to a higher resolution than one second. The
453 functions and the associated data types described in this section are
454 declared in @file{sys/time.h}.
455 @pindex sys/time.h
456
457 @comment sys/time.h
458 @comment BSD
459 @deftp {Data Type} {struct timezone}
460 The @code{struct timezone} structure is used to hold minimal information
461 about the local time zone. It has the following members:
462
463 @table @code
464 @item int tz_minuteswest
465 This is the number of minutes west of UTC.
466
467 @item int tz_dsttime
468 If nonzero, Daylight Saving Time applies during some part of the year.
469 @end table
470
471 The @code{struct timezone} type is obsolete and should never be used.
472 Instead, use the facilities described in @ref{Time Zone Functions}.
473 @end deftp
474
475 @comment sys/time.h
476 @comment BSD
477 @deftypefun int gettimeofday (struct timeval *@var{tp}, struct timezone *@var{tzp})
478 The @code{gettimeofday} function returns the current calendar time as
479 the elapsed time since the epoch in the @code{struct timeval} structure
480 indicated by @var{tp}. (@pxref{Elapsed Time} for a description of
481 @code{struct timeval}). Information about the time zone is returned in
482 the structure pointed at @var{tzp}. If the @var{tzp} argument is a null
483 pointer, time zone information is ignored.
484
485 The return value is @code{0} on success and @code{-1} on failure. The
486 following @code{errno} error condition is defined for this function:
487
488 @table @code
489 @item ENOSYS
490 The operating system does not support getting time zone information, and
491 @var{tzp} is not a null pointer. @gnusystems{} do not
492 support using @w{@code{struct timezone}} to represent time zone
493 information; that is an obsolete feature of 4.3 BSD.
494 Instead, use the facilities described in @ref{Time Zone Functions}.
495 @end table
496 @end deftypefun
497
498 @comment sys/time.h
499 @comment BSD
500 @deftypefun int settimeofday (const struct timeval *@var{tp}, const struct timezone *@var{tzp})
501 The @code{settimeofday} function sets the current calendar time in the
502 system clock according to the arguments. As for @code{gettimeofday},
503 the calendar time is represented as the elapsed time since the epoch.
504 As for @code{gettimeofday}, time zone information is ignored if
505 @var{tzp} is a null pointer.
506
507 You must be a privileged user in order to use @code{settimeofday}.
508
509 Some kernels automatically set the system clock from some source such as
510 a hardware clock when they start up. Others, including Linux, place the
511 system clock in an ``invalid'' state (in which attempts to read the clock
512 fail). A call of @code{stime} removes the system clock from an invalid
513 state, and system startup scripts typically run a program that calls
514 @code{stime}.
515
516 @code{settimeofday} causes a sudden jump forwards or backwards, which
517 can cause a variety of problems in a system. Use @code{adjtime} (below)
518 to make a smooth transition from one time to another by temporarily
519 speeding up or slowing down the clock.
520
521 With a Linux kernel, @code{adjtimex} does the same thing and can also
522 make permanent changes to the speed of the system clock so it doesn't
523 need to be corrected as often.
524
525 The return value is @code{0} on success and @code{-1} on failure. The
526 following @code{errno} error conditions are defined for this function:
527
528 @table @code
529 @item EPERM
530 This process cannot set the clock because it is not privileged.
531
532 @item ENOSYS
533 The operating system does not support setting time zone information, and
534 @var{tzp} is not a null pointer.
535 @end table
536 @end deftypefun
537
538 @c On Linux, GNU libc implements adjtime() as a call to adjtimex().
539 @comment sys/time.h
540 @comment BSD
541 @deftypefun int adjtime (const struct timeval *@var{delta}, struct timeval *@var{olddelta})
542 This function speeds up or slows down the system clock in order to make
543 a gradual adjustment. This ensures that the calendar time reported by
544 the system clock is always monotonically increasing, which might not
545 happen if you simply set the clock.
546
547 The @var{delta} argument specifies a relative adjustment to be made to
548 the clock time. If negative, the system clock is slowed down for a
549 while until it has lost this much elapsed time. If positive, the system
550 clock is speeded up for a while.
551
552 If the @var{olddelta} argument is not a null pointer, the @code{adjtime}
553 function returns information about any previous time adjustment that
554 has not yet completed.
555
556 This function is typically used to synchronize the clocks of computers
557 in a local network. You must be a privileged user to use it.
558
559 With a Linux kernel, you can use the @code{adjtimex} function to
560 permanently change the clock speed.
561
562 The return value is @code{0} on success and @code{-1} on failure. The
563 following @code{errno} error condition is defined for this function:
564
565 @table @code
566 @item EPERM
567 You do not have privilege to set the time.
568 @end table
569 @end deftypefun
570
571 @strong{Portability Note:} The @code{gettimeofday}, @code{settimeofday},
572 and @code{adjtime} functions are derived from BSD.
573
574
575 Symbols for the following function are declared in @file{sys/timex.h}.
576
577 @comment sys/timex.h
578 @comment GNU
579 @deftypefun int adjtimex (struct timex *@var{timex})
580
581 @code{adjtimex} is functionally identical to @code{ntp_adjtime}.
582 @xref{High Accuracy Clock}.
583
584 This function is present only with a Linux kernel.
585
586 @end deftypefun
587
588 @node Broken-down Time
589 @subsection Broken-down Time
590 @cindex broken-down time
591 @cindex calendar time and broken-down time
592
593 Calendar time is represented by the usual @glibcadj{} functions as an
594 elapsed time since a fixed base calendar time. This is convenient for
595 computation, but has no relation to the way people normally think of
596 calendar time. By contrast, @dfn{broken-down time} is a binary
597 representation of calendar time separated into year, month, day, and so
598 on. Broken-down time values are not useful for calculations, but they
599 are useful for printing human readable time information.
600
601 A broken-down time value is always relative to a choice of time
602 zone, and it also indicates which time zone that is.
603
604 The symbols in this section are declared in the header file @file{time.h}.
605
606 @comment time.h
607 @comment ISO
608 @deftp {Data Type} {struct tm}
609 This is the data type used to represent a broken-down time. The structure
610 contains at least the following members, which can appear in any order.
611
612 @table @code
613 @item int tm_sec
614 This is the number of full seconds since the top of the minute (normally
615 in the range @code{0} through @code{59}, but the actual upper limit is
616 @code{60}, to allow for leap seconds if leap second support is
617 available).
618 @cindex leap second
619
620 @item int tm_min
621 This is the number of full minutes since the top of the hour (in the
622 range @code{0} through @code{59}).
623
624 @item int tm_hour
625 This is the number of full hours past midnight (in the range @code{0} through
626 @code{23}).
627
628 @item int tm_mday
629 This is the ordinal day of the month (in the range @code{1} through @code{31}).
630 Watch out for this one! As the only ordinal number in the structure, it is
631 inconsistent with the rest of the structure.
632
633 @item int tm_mon
634 This is the number of full calendar months since the beginning of the
635 year (in the range @code{0} through @code{11}). Watch out for this one!
636 People usually use ordinal numbers for month-of-year (where January = 1).
637
638 @item int tm_year
639 This is the number of full calendar years since 1900.
640
641 @item int tm_wday
642 This is the number of full days since Sunday (in the range @code{0} through
643 @code{6}).
644
645 @item int tm_yday
646 This is the number of full days since the beginning of the year (in the
647 range @code{0} through @code{365}).
648
649 @item int tm_isdst
650 @cindex Daylight Saving Time
651 @cindex summer time
652 This is a flag that indicates whether Daylight Saving Time is (or was, or
653 will be) in effect at the time described. The value is positive if
654 Daylight Saving Time is in effect, zero if it is not, and negative if the
655 information is not available.
656
657 @item long int tm_gmtoff
658 This field describes the time zone that was used to compute this
659 broken-down time value, including any adjustment for daylight saving; it
660 is the number of seconds that you must add to UTC to get local time.
661 You can also think of this as the number of seconds east of UTC. For
662 example, for U.S. Eastern Standard Time, the value is @code{-5*60*60}.
663 The @code{tm_gmtoff} field is derived from BSD and is a GNU library
664 extension; it is not visible in a strict @w{ISO C} environment.
665
666 @item const char *tm_zone
667 This field is the name for the time zone that was used to compute this
668 broken-down time value. Like @code{tm_gmtoff}, this field is a BSD and
669 GNU extension, and is not visible in a strict @w{ISO C} environment.
670 @end table
671 @end deftp
672
673
674 @comment time.h
675 @comment ISO
676 @deftypefun {struct tm *} localtime (const time_t *@var{time})
677 The @code{localtime} function converts the simple time pointed to by
678 @var{time} to broken-down time representation, expressed relative to the
679 user's specified time zone.
680
681 The return value is a pointer to a static broken-down time structure, which
682 might be overwritten by subsequent calls to @code{ctime}, @code{gmtime},
683 or @code{localtime}. (But no other library function overwrites the contents
684 of this object.)
685
686 The return value is the null pointer if @var{time} cannot be represented
687 as a broken-down time; typically this is because the year cannot fit into
688 an @code{int}.
689
690 Calling @code{localtime} also sets the current time zone as if
691 @code{tzset} were called. @xref{Time Zone Functions}.
692 @end deftypefun
693
694 Using the @code{localtime} function is a big problem in multi-threaded
695 programs. The result is returned in a static buffer and this is used in
696 all threads. POSIX.1c introduced a variant of this function.
697
698 @comment time.h
699 @comment POSIX.1c
700 @deftypefun {struct tm *} localtime_r (const time_t *@var{time}, struct tm *@var{resultp})
701 The @code{localtime_r} function works just like the @code{localtime}
702 function. It takes a pointer to a variable containing a simple time
703 and converts it to the broken-down time format.
704
705 But the result is not placed in a static buffer. Instead it is placed
706 in the object of type @code{struct tm} to which the parameter
707 @var{resultp} points.
708
709 If the conversion is successful the function returns a pointer to the
710 object the result was written into, i.e., it returns @var{resultp}.
711 @end deftypefun
712
713
714 @comment time.h
715 @comment ISO
716 @deftypefun {struct tm *} gmtime (const time_t *@var{time})
717 This function is similar to @code{localtime}, except that the broken-down
718 time is expressed as Coordinated Universal Time (UTC) (formerly called
719 Greenwich Mean Time (GMT)) rather than relative to a local time zone.
720
721 @end deftypefun
722
723 As for the @code{localtime} function we have the problem that the result
724 is placed in a static variable. POSIX.1c also provides a replacement for
725 @code{gmtime}.
726
727 @comment time.h
728 @comment POSIX.1c
729 @deftypefun {struct tm *} gmtime_r (const time_t *@var{time}, struct tm *@var{resultp})
730 This function is similar to @code{localtime_r}, except that it converts
731 just like @code{gmtime} the given time as Coordinated Universal Time.
732
733 If the conversion is successful the function returns a pointer to the
734 object the result was written into, i.e., it returns @var{resultp}.
735 @end deftypefun
736
737
738 @comment time.h
739 @comment ISO
740 @deftypefun time_t mktime (struct tm *@var{brokentime})
741 The @code{mktime} function converts a broken-down time structure to a
742 simple time representation. It also normalizes the contents of the
743 broken-down time structure, and fills in some components based on the
744 values of the others.
745
746 The @code{mktime} function ignores the specified contents of the
747 @code{tm_wday}, @code{tm_yday}, @code{tm_gmtoff}, and @code{tm_zone}
748 members of the broken-down time
749 structure. It uses the values of the other components to determine the
750 calendar time; it's permissible for these components to have
751 unnormalized values outside their normal ranges. The last thing that
752 @code{mktime} does is adjust the components of the @var{brokentime}
753 structure, including the members that were initally ignored.
754
755 If the specified broken-down time cannot be represented as a simple time,
756 @code{mktime} returns a value of @code{(time_t)(-1)} and does not modify
757 the contents of @var{brokentime}.
758
759 Calling @code{mktime} also sets the current time zone as if
760 @code{tzset} were called; @code{mktime} uses this information instead
761 of @var{brokentime}'s initial @code{tm_gmtoff} and @code{tm_zone}
762 members. @xref{Time Zone Functions}.
763 @end deftypefun
764
765 @comment time.h
766 @comment ???
767 @deftypefun time_t timelocal (struct tm *@var{brokentime})
768
769 @code{timelocal} is functionally identical to @code{mktime}, but more
770 mnemonically named. Note that it is the inverse of the @code{localtime}
771 function.
772
773 @strong{Portability note:} @code{mktime} is essentially universally
774 available. @code{timelocal} is rather rare.
775
776 @end deftypefun
777
778 @comment time.h
779 @comment ???
780 @deftypefun time_t timegm (struct tm *@var{brokentime})
781
782 @code{timegm} is functionally identical to @code{mktime} except it
783 always takes the input values to be Coordinated Universal Time (UTC)
784 regardless of any local time zone setting.
785
786 Note that @code{timegm} is the inverse of @code{gmtime}.
787
788 @strong{Portability note:} @code{mktime} is essentially universally
789 available. @code{timegm} is rather rare. For the most portable
790 conversion from a UTC broken-down time to a simple time, set
791 the @code{TZ} environment variable to UTC, call @code{mktime}, then set
792 @code{TZ} back.
793
794 @end deftypefun
795
796
797
798 @node High Accuracy Clock
799 @subsection High Accuracy Clock
800
801 @cindex time, high precision
802 @cindex clock, high accuracy
803 @pindex sys/timex.h
804 @c On Linux, GNU libc implements ntp_gettime() and npt_adjtime() as calls
805 @c to adjtimex().
806 The @code{ntp_gettime} and @code{ntp_adjtime} functions provide an
807 interface to monitor and manipulate the system clock to maintain high
808 accuracy time. For example, you can fine tune the speed of the clock
809 or synchronize it with another time source.
810
811 A typical use of these functions is by a server implementing the Network
812 Time Protocol to synchronize the clocks of multiple systems and high
813 precision clocks.
814
815 These functions are declared in @file{sys/timex.h}.
816
817 @tindex struct ntptimeval
818 @deftp {Data Type} {struct ntptimeval}
819 This structure is used for information about the system clock. It
820 contains the following members:
821 @table @code
822 @item struct timeval time
823 This is the current calendar time, expressed as the elapsed time since
824 the epoch. The @code{struct timeval} data type is described in
825 @ref{Elapsed Time}.
826
827 @item long int maxerror
828 This is the maximum error, measured in microseconds. Unless updated
829 via @code{ntp_adjtime} periodically, this value will reach some
830 platform-specific maximum value.
831
832 @item long int esterror
833 This is the estimated error, measured in microseconds. This value can
834 be set by @code{ntp_adjtime} to indicate the estimated offset of the
835 system clock from the true calendar time.
836 @end table
837 @end deftp
838
839 @comment sys/timex.h
840 @comment GNU
841 @deftypefun int ntp_gettime (struct ntptimeval *@var{tptr})
842 The @code{ntp_gettime} function sets the structure pointed to by
843 @var{tptr} to current values. The elements of the structure afterwards
844 contain the values the timer implementation in the kernel assumes. They
845 might or might not be correct. If they are not a @code{ntp_adjtime}
846 call is necessary.
847
848 The return value is @code{0} on success and other values on failure. The
849 following @code{errno} error conditions are defined for this function:
850
851 @table @code
852 @item TIME_ERROR
853 The precision clock model is not properly set up at the moment, thus the
854 clock must be considered unsynchronized, and the values should be
855 treated with care.
856 @end table
857 @end deftypefun
858
859 @tindex struct timex
860 @deftp {Data Type} {struct timex}
861 This structure is used to control and monitor the system clock. It
862 contains the following members:
863 @table @code
864 @item unsigned int modes
865 This variable controls whether and which values are set. Several
866 symbolic constants have to be combined with @emph{binary or} to specify
867 the effective mode. These constants start with @code{MOD_}.
868
869 @item long int offset
870 This value indicates the current offset of the system clock from the true
871 calendar time. The value is given in microseconds. If bit
872 @code{MOD_OFFSET} is set in @code{modes}, the offset (and possibly other
873 dependent values) can be set. The offset's absolute value must not
874 exceed @code{MAXPHASE}.
875
876
877 @item long int frequency
878 This value indicates the difference in frequency between the true
879 calendar time and the system clock. The value is expressed as scaled
880 PPM (parts per million, 0.0001%). The scaling is @code{1 <<
881 SHIFT_USEC}. The value can be set with bit @code{MOD_FREQUENCY}, but
882 the absolute value must not exceed @code{MAXFREQ}.
883
884 @item long int maxerror
885 This is the maximum error, measured in microseconds. A new value can be
886 set using bit @code{MOD_MAXERROR}. Unless updated via
887 @code{ntp_adjtime} periodically, this value will increase steadily
888 and reach some platform-specific maximum value.
889
890 @item long int esterror
891 This is the estimated error, measured in microseconds. This value can
892 be set using bit @code{MOD_ESTERROR}.
893
894 @item int status
895 This variable reflects the various states of the clock machinery. There
896 are symbolic constants for the significant bits, starting with
897 @code{STA_}. Some of these flags can be updated using the
898 @code{MOD_STATUS} bit.
899
900 @item long int constant
901 This value represents the bandwidth or stiffness of the PLL (phase
902 locked loop) implemented in the kernel. The value can be changed using
903 bit @code{MOD_TIMECONST}.
904
905 @item long int precision
906 This value represents the accuracy or the maximum error when reading the
907 system clock. The value is expressed in microseconds.
908
909 @item long int tolerance
910 This value represents the maximum frequency error of the system clock in
911 scaled PPM. This value is used to increase the @code{maxerror} every
912 second.
913
914 @item struct timeval time
915 The current calendar time.
916
917 @item long int tick
918 The elapsed time between clock ticks in microseconds. A clock tick is a
919 periodic timer interrupt on which the system clock is based.
920
921 @item long int ppsfreq
922 This is the first of a few optional variables that are present only if
923 the system clock can use a PPS (pulse per second) signal to discipline
924 the system clock. The value is expressed in scaled PPM and it denotes
925 the difference in frequency between the system clock and the PPS signal.
926
927 @item long int jitter
928 This value expresses a median filtered average of the PPS signal's
929 dispersion in microseconds.
930
931 @item int shift
932 This value is a binary exponent for the duration of the PPS calibration
933 interval, ranging from @code{PPS_SHIFT} to @code{PPS_SHIFTMAX}.
934
935 @item long int stabil
936 This value represents the median filtered dispersion of the PPS
937 frequency in scaled PPM.
938
939 @item long int jitcnt
940 This counter represents the number of pulses where the jitter exceeded
941 the allowed maximum @code{MAXTIME}.
942
943 @item long int calcnt
944 This counter reflects the number of successful calibration intervals.
945
946 @item long int errcnt
947 This counter represents the number of calibration errors (caused by
948 large offsets or jitter).
949
950 @item long int stbcnt
951 This counter denotes the number of calibrations where the stability
952 exceeded the threshold.
953 @end table
954 @end deftp
955
956 @comment sys/timex.h
957 @comment GNU
958 @deftypefun int ntp_adjtime (struct timex *@var{tptr})
959 The @code{ntp_adjtime} function sets the structure specified by
960 @var{tptr} to current values.
961
962 In addition, @code{ntp_adjtime} updates some settings to match what you
963 pass to it in *@var{tptr}. Use the @code{modes} element of *@var{tptr}
964 to select what settings to update. You can set @code{offset},
965 @code{freq}, @code{maxerror}, @code{esterror}, @code{status},
966 @code{constant}, and @code{tick}.
967
968 @code{modes} = zero means set nothing.
969
970 Only the superuser can update settings.
971
972 @c On Linux, ntp_adjtime() also does the adjtime() function if you set
973 @c modes = ADJ_OFFSET_SINGLESHOT (in fact, that is how GNU libc implements
974 @c adjtime()). But this should be considered an internal function because
975 @c it's so inconsistent with the rest of what ntp_adjtime() does and is
976 @c forced in an ugly way into the struct timex. So we don't document it
977 @c and instead document adjtime() as the way to achieve the function.
978
979 The return value is @code{0} on success and other values on failure. The
980 following @code{errno} error conditions are defined for this function:
981
982 @table @code
983 @item TIME_ERROR
984 The high accuracy clock model is not properly set up at the moment, thus the
985 clock must be considered unsynchronized, and the values should be
986 treated with care. Another reason could be that the specified new values
987 are not allowed.
988
989 @item EPERM
990 The process specified a settings update, but is not superuser.
991
992 @end table
993
994 For more details see RFC1305 (Network Time Protocol, Version 3) and
995 related documents.
996
997 @strong{Portability note:} Early versions of @theglibc{} did not
998 have this function but did have the synonymous @code{adjtimex}.
999
1000 @end deftypefun
1001
1002
1003 @node Formatting Calendar Time
1004 @subsection Formatting Calendar Time
1005
1006 The functions described in this section format calendar time values as
1007 strings. These functions are declared in the header file @file{time.h}.
1008 @pindex time.h
1009
1010 @comment time.h
1011 @comment ISO
1012 @deftypefun {char *} asctime (const struct tm *@var{brokentime})
1013 The @code{asctime} function converts the broken-down time value that
1014 @var{brokentime} points to into a string in a standard format:
1015
1016 @smallexample
1017 "Tue May 21 13:46:22 1991\n"
1018 @end smallexample
1019
1020 The abbreviations for the days of week are: @samp{Sun}, @samp{Mon},
1021 @samp{Tue}, @samp{Wed}, @samp{Thu}, @samp{Fri}, and @samp{Sat}.
1022
1023 The abbreviations for the months are: @samp{Jan}, @samp{Feb},
1024 @samp{Mar}, @samp{Apr}, @samp{May}, @samp{Jun}, @samp{Jul}, @samp{Aug},
1025 @samp{Sep}, @samp{Oct}, @samp{Nov}, and @samp{Dec}.
1026
1027 The return value points to a statically allocated string, which might be
1028 overwritten by subsequent calls to @code{asctime} or @code{ctime}.
1029 (But no other library function overwrites the contents of this
1030 string.)
1031 @end deftypefun
1032
1033 @comment time.h
1034 @comment POSIX.1c
1035 @deftypefun {char *} asctime_r (const struct tm *@var{brokentime}, char *@var{buffer})
1036 This function is similar to @code{asctime} but instead of placing the
1037 result in a static buffer it writes the string in the buffer pointed to
1038 by the parameter @var{buffer}. This buffer should have room
1039 for at least 26 bytes, including the terminating null.
1040
1041 If no error occurred the function returns a pointer to the string the
1042 result was written into, i.e., it returns @var{buffer}. Otherwise
1043 return @code{NULL}.
1044 @end deftypefun
1045
1046
1047 @comment time.h
1048 @comment ISO
1049 @deftypefun {char *} ctime (const time_t *@var{time})
1050 The @code{ctime} function is similar to @code{asctime}, except that you
1051 specify the calendar time argument as a @code{time_t} simple time value
1052 rather than in broken-down local time format. It is equivalent to
1053
1054 @smallexample
1055 asctime (localtime (@var{time}))
1056 @end smallexample
1057
1058 Calling @code{ctime} also sets the current time zone as if
1059 @code{tzset} were called. @xref{Time Zone Functions}.
1060 @end deftypefun
1061
1062 @comment time.h
1063 @comment POSIX.1c
1064 @deftypefun {char *} ctime_r (const time_t *@var{time}, char *@var{buffer})
1065 This function is similar to @code{ctime}, but places the result in the
1066 string pointed to by @var{buffer}. It is equivalent to (written using
1067 gcc extensions, @pxref{Statement Exprs,,,gcc,Porting and Using gcc}):
1068
1069 @smallexample
1070 (@{ struct tm tm; asctime_r (localtime_r (time, &tm), buf); @})
1071 @end smallexample
1072
1073 If no error occurred the function returns a pointer to the string the
1074 result was written into, i.e., it returns @var{buffer}. Otherwise
1075 return @code{NULL}.
1076 @end deftypefun
1077
1078
1079 @comment time.h
1080 @comment ISO
1081 @deftypefun size_t strftime (char *@var{s}, size_t @var{size}, const char *@var{template}, const struct tm *@var{brokentime})
1082 This function is similar to the @code{sprintf} function (@pxref{Formatted
1083 Input}), but the conversion specifications that can appear in the format
1084 template @var{template} are specialized for printing components of the date
1085 and time @var{brokentime} according to the locale currently specified for
1086 time conversion (@pxref{Locales}) and the current time zone
1087 (@pxref{Time Zone Functions}).
1088
1089 Ordinary characters appearing in the @var{template} are copied to the
1090 output string @var{s}; this can include multibyte character sequences.
1091 Conversion specifiers are introduced by a @samp{%} character, followed
1092 by an optional flag which can be one of the following. These flags
1093 are all GNU extensions. The first three affect only the output of
1094 numbers:
1095
1096 @table @code
1097 @item _
1098 The number is padded with spaces.
1099
1100 @item -
1101 The number is not padded at all.
1102
1103 @item 0
1104 The number is padded with zeros even if the format specifies padding
1105 with spaces.
1106
1107 @item ^
1108 The output uses uppercase characters, but only if this is possible
1109 (@pxref{Case Conversion}).
1110 @end table
1111
1112 The default action is to pad the number with zeros to keep it a constant
1113 width. Numbers that do not have a range indicated below are never
1114 padded, since there is no natural width for them.
1115
1116 Following the flag an optional specification of the width is possible.
1117 This is specified in decimal notation. If the natural size of the
1118 output is of the field has less than the specified number of characters,
1119 the result is written right adjusted and space padded to the given
1120 size.
1121
1122 An optional modifier can follow the optional flag and width
1123 specification. The modifiers, which were first standardized by
1124 POSIX.2-1992 and by @w{ISO C99}, are:
1125
1126 @table @code
1127 @item E
1128 Use the locale's alternate representation for date and time. This
1129 modifier applies to the @code{%c}, @code{%C}, @code{%x}, @code{%X},
1130 @code{%y} and @code{%Y} format specifiers. In a Japanese locale, for
1131 example, @code{%Ex} might yield a date format based on the Japanese
1132 Emperors' reigns.
1133
1134 @item O
1135 Use the locale's alternate numeric symbols for numbers. This modifier
1136 applies only to numeric format specifiers.
1137 @end table
1138
1139 If the format supports the modifier but no alternate representation
1140 is available, it is ignored.
1141
1142 The conversion specifier ends with a format specifier taken from the
1143 following list. The whole @samp{%} sequence is replaced in the output
1144 string as follows:
1145
1146 @table @code
1147 @item %a
1148 The abbreviated weekday name according to the current locale.
1149
1150 @item %A
1151 The full weekday name according to the current locale.
1152
1153 @item %b
1154 The abbreviated month name according to the current locale.
1155
1156 @item %B
1157 The full month name according to the current locale.
1158
1159 Using @code{%B} together with @code{%d} produces grammatically
1160 incorrect results for some locales.
1161
1162 @item %c
1163 The preferred calendar time representation for the current locale.
1164
1165 @item %C
1166 The century of the year. This is equivalent to the greatest integer not
1167 greater than the year divided by 100.
1168
1169 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1170
1171 @item %d
1172 The day of the month as a decimal number (range @code{01} through @code{31}).
1173
1174 @item %D
1175 The date using the format @code{%m/%d/%y}.
1176
1177 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1178
1179 @item %e
1180 The day of the month like with @code{%d}, but padded with blank (range
1181 @code{ 1} through @code{31}).
1182
1183 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1184
1185 @item %F
1186 The date using the format @code{%Y-%m-%d}. This is the form specified
1187 in the @w{ISO 8601} standard and is the preferred form for all uses.
1188
1189 This format was first standardized by @w{ISO C99} and by POSIX.1-2001.
1190
1191 @item %g
1192 The year corresponding to the ISO week number, but without the century
1193 (range @code{00} through @code{99}). This has the same format and value
1194 as @code{%y}, except that if the ISO week number (see @code{%V}) belongs
1195 to the previous or next year, that year is used instead.
1196
1197 This format was first standardized by @w{ISO C99} and by POSIX.1-2001.
1198
1199 @item %G
1200 The year corresponding to the ISO week number. This has the same format
1201 and value as @code{%Y}, except that if the ISO week number (see
1202 @code{%V}) belongs to the previous or next year, that year is used
1203 instead.
1204
1205 This format was first standardized by @w{ISO C99} and by POSIX.1-2001
1206 but was previously available as a GNU extension.
1207
1208 @item %h
1209 The abbreviated month name according to the current locale. The action
1210 is the same as for @code{%b}.
1211
1212 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1213
1214 @item %H
1215 The hour as a decimal number, using a 24-hour clock (range @code{00} through
1216 @code{23}).
1217
1218 @item %I
1219 The hour as a decimal number, using a 12-hour clock (range @code{01} through
1220 @code{12}).
1221
1222 @item %j
1223 The day of the year as a decimal number (range @code{001} through @code{366}).
1224
1225 @item %k
1226 The hour as a decimal number, using a 24-hour clock like @code{%H}, but
1227 padded with blank (range @code{ 0} through @code{23}).
1228
1229 This format is a GNU extension.
1230
1231 @item %l
1232 The hour as a decimal number, using a 12-hour clock like @code{%I}, but
1233 padded with blank (range @code{ 1} through @code{12}).
1234
1235 This format is a GNU extension.
1236
1237 @item %m
1238 The month as a decimal number (range @code{01} through @code{12}).
1239
1240 @item %M
1241 The minute as a decimal number (range @code{00} through @code{59}).
1242
1243 @item %n
1244 A single @samp{\n} (newline) character.
1245
1246 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1247
1248 @item %p
1249 Either @samp{AM} or @samp{PM}, according to the given time value; or the
1250 corresponding strings for the current locale. Noon is treated as
1251 @samp{PM} and midnight as @samp{AM}. In most locales
1252 @samp{AM}/@samp{PM} format is not supported, in such cases @code{"%p"}
1253 yields an empty string.
1254
1255 @ignore
1256 We currently have a problem with makeinfo. Write @samp{AM} and @samp{am}
1257 both results in `am'. I.e., the difference in case is not visible anymore.
1258 @end ignore
1259 @item %P
1260 Either @samp{am} or @samp{pm}, according to the given time value; or the
1261 corresponding strings for the current locale, printed in lowercase
1262 characters. Noon is treated as @samp{pm} and midnight as @samp{am}. In
1263 most locales @samp{AM}/@samp{PM} format is not supported, in such cases
1264 @code{"%P"} yields an empty string.
1265
1266 This format is a GNU extension.
1267
1268 @item %r
1269 The complete calendar time using the AM/PM format of the current locale.
1270
1271 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1272 In the POSIX locale, this format is equivalent to @code{%I:%M:%S %p}.
1273
1274 @item %R
1275 The hour and minute in decimal numbers using the format @code{%H:%M}.
1276
1277 This format was first standardized by @w{ISO C99} and by POSIX.1-2001
1278 but was previously available as a GNU extension.
1279
1280 @item %s
1281 The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
1282 Leap seconds are not counted unless leap second support is available.
1283
1284 This format is a GNU extension.
1285
1286 @item %S
1287 The seconds as a decimal number (range @code{00} through @code{60}).
1288
1289 @item %t
1290 A single @samp{\t} (tabulator) character.
1291
1292 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1293
1294 @item %T
1295 The time of day using decimal numbers using the format @code{%H:%M:%S}.
1296
1297 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1298
1299 @item %u
1300 The day of the week as a decimal number (range @code{1} through
1301 @code{7}), Monday being @code{1}.
1302
1303 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1304
1305 @item %U
1306 The week number of the current year as a decimal number (range @code{00}
1307 through @code{53}), starting with the first Sunday as the first day of
1308 the first week. Days preceding the first Sunday in the year are
1309 considered to be in week @code{00}.
1310
1311 @item %V
1312 The @w{ISO 8601:1988} week number as a decimal number (range @code{01}
1313 through @code{53}). ISO weeks start with Monday and end with Sunday.
1314 Week @code{01} of a year is the first week which has the majority of its
1315 days in that year; this is equivalent to the week containing the year's
1316 first Thursday, and it is also equivalent to the week containing January
1317 4. Week @code{01} of a year can contain days from the previous year.
1318 The week before week @code{01} of a year is the last week (@code{52} or
1319 @code{53}) of the previous year even if it contains days from the new
1320 year.
1321
1322 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1323
1324 @item %w
1325 The day of the week as a decimal number (range @code{0} through
1326 @code{6}), Sunday being @code{0}.
1327
1328 @item %W
1329 The week number of the current year as a decimal number (range @code{00}
1330 through @code{53}), starting with the first Monday as the first day of
1331 the first week. All days preceding the first Monday in the year are
1332 considered to be in week @code{00}.
1333
1334 @item %x
1335 The preferred date representation for the current locale.
1336
1337 @item %X
1338 The preferred time of day representation for the current locale.
1339
1340 @item %y
1341 The year without a century as a decimal number (range @code{00} through
1342 @code{99}). This is equivalent to the year modulo 100.
1343
1344 @item %Y
1345 The year as a decimal number, using the Gregorian calendar. Years
1346 before the year @code{1} are numbered @code{0}, @code{-1}, and so on.
1347
1348 @item %z
1349 @w{RFC 822}/@w{ISO 8601:1988} style numeric time zone (e.g.,
1350 @code{-0600} or @code{+0100}), or nothing if no time zone is
1351 determinable.
1352
1353 This format was first standardized by @w{ISO C99} and by POSIX.1-2001
1354 but was previously available as a GNU extension.
1355
1356 In the POSIX locale, a full @w{RFC 822} timestamp is generated by the format
1357 @w{@samp{"%a, %d %b %Y %H:%M:%S %z"}} (or the equivalent
1358 @w{@samp{"%a, %d %b %Y %T %z"}}).
1359
1360 @item %Z
1361 The time zone abbreviation (empty if the time zone can't be determined).
1362
1363 @item %%
1364 A literal @samp{%} character.
1365 @end table
1366
1367 The @var{size} parameter can be used to specify the maximum number of
1368 characters to be stored in the array @var{s}, including the terminating
1369 null character. If the formatted time requires more than @var{size}
1370 characters, @code{strftime} returns zero and the contents of the array
1371 @var{s} are undefined. Otherwise the return value indicates the
1372 number of characters placed in the array @var{s}, not including the
1373 terminating null character.
1374
1375 @emph{Warning:} This convention for the return value which is prescribed
1376 in @w{ISO C} can lead to problems in some situations. For certain
1377 format strings and certain locales the output really can be the empty
1378 string and this cannot be discovered by testing the return value only.
1379 E.g., in most locales the AM/PM time format is not supported (most of
1380 the world uses the 24 hour time representation). In such locales
1381 @code{"%p"} will return the empty string, i.e., the return value is
1382 zero. To detect situations like this something similar to the following
1383 code should be used:
1384
1385 @smallexample
1386 buf[0] = '\1';
1387 len = strftime (buf, bufsize, format, tp);
1388 if (len == 0 && buf[0] != '\0')
1389 @{
1390 /* Something went wrong in the strftime call. */
1391 @dots{}
1392 @}
1393 @end smallexample
1394
1395 If @var{s} is a null pointer, @code{strftime} does not actually write
1396 anything, but instead returns the number of characters it would have written.
1397
1398 Calling @code{strftime} also sets the current time zone as if
1399 @code{tzset} were called; @code{strftime} uses this information
1400 instead of @var{brokentime}'s @code{tm_gmtoff} and @code{tm_zone}
1401 members. @xref{Time Zone Functions}.
1402
1403 For an example of @code{strftime}, see @ref{Time Functions Example}.
1404 @end deftypefun
1405
1406 @comment time.h
1407 @comment ISO/Amend1
1408 @deftypefun size_t wcsftime (wchar_t *@var{s}, size_t @var{size}, const wchar_t *@var{template}, const struct tm *@var{brokentime})
1409 The @code{wcsftime} function is equivalent to the @code{strftime}
1410 function with the difference that it operates on wide character
1411 strings. The buffer where the result is stored, pointed to by @var{s},
1412 must be an array of wide characters. The parameter @var{size} which
1413 specifies the size of the output buffer gives the number of wide
1414 character, not the number of bytes.
1415
1416 Also the format string @var{template} is a wide character string. Since
1417 all characters needed to specify the format string are in the basic
1418 character set it is portably possible to write format strings in the C
1419 source code using the @code{L"@dots{}"} notation. The parameter
1420 @var{brokentime} has the same meaning as in the @code{strftime} call.
1421
1422 The @code{wcsftime} function supports the same flags, modifiers, and
1423 format specifiers as the @code{strftime} function.
1424
1425 The return value of @code{wcsftime} is the number of wide characters
1426 stored in @code{s}. When more characters would have to be written than
1427 can be placed in the buffer @var{s} the return value is zero, with the
1428 same problems indicated in the @code{strftime} documentation.
1429 @end deftypefun
1430
1431 @node Parsing Date and Time
1432 @subsection Convert textual time and date information back
1433
1434 The @w{ISO C} standard does not specify any functions which can convert
1435 the output of the @code{strftime} function back into a binary format.
1436 This led to a variety of more-or-less successful implementations with
1437 different interfaces over the years. Then the Unix standard was
1438 extended by the addition of two functions: @code{strptime} and
1439 @code{getdate}. Both have strange interfaces but at least they are
1440 widely available.
1441
1442 @menu
1443 * Low-Level Time String Parsing:: Interpret string according to given format.
1444 * General Time String Parsing:: User-friendly function to parse data and
1445 time strings.
1446 @end menu
1447
1448 @node Low-Level Time String Parsing
1449 @subsubsection Interpret string according to given format
1450
1451 The first function is rather low-level. It is nevertheless frequently
1452 used in software since it is better known. Its interface and
1453 implementation are heavily influenced by the @code{getdate} function,
1454 which is defined and implemented in terms of calls to @code{strptime}.
1455
1456 @comment time.h
1457 @comment XPG4
1458 @deftypefun {char *} strptime (const char *@var{s}, const char *@var{fmt}, struct tm *@var{tp})
1459 The @code{strptime} function parses the input string @var{s} according
1460 to the format string @var{fmt} and stores its results in the
1461 structure @var{tp}.
1462
1463 The input string could be generated by a @code{strftime} call or
1464 obtained any other way. It does not need to be in a human-recognizable
1465 format; e.g. a date passed as @code{"02:1999:9"} is acceptable, even
1466 though it is ambiguous without context. As long as the format string
1467 @var{fmt} matches the input string the function will succeed.
1468
1469 The user has to make sure, though, that the input can be parsed in a
1470 unambiguous way. The string @code{"1999112"} can be parsed using the
1471 format @code{"%Y%m%d"} as 1999-1-12, 1999-11-2, or even 19991-1-2. It
1472 is necessary to add appropriate separators to reliably get results.
1473
1474 The format string consists of the same components as the format string
1475 of the @code{strftime} function. The only difference is that the flags
1476 @code{_}, @code{-}, @code{0}, and @code{^} are not allowed.
1477 @comment Is this really the intention? --drepper
1478 Several of the distinct formats of @code{strftime} do the same work in
1479 @code{strptime} since differences like case of the input do not matter.
1480 For reasons of symmetry all formats are supported, though.
1481
1482 The modifiers @code{E} and @code{O} are also allowed everywhere the
1483 @code{strftime} function allows them.
1484
1485 The formats are:
1486
1487 @table @code
1488 @item %a
1489 @itemx %A
1490 The weekday name according to the current locale, in abbreviated form or
1491 the full name.
1492
1493 @item %b
1494 @itemx %B
1495 @itemx %h
1496 The month name according to the current locale, in abbreviated form or
1497 the full name.
1498
1499 @item %c
1500 The date and time representation for the current locale.
1501
1502 @item %Ec
1503 Like @code{%c} but the locale's alternative date and time format is used.
1504
1505 @item %C
1506 The century of the year.
1507
1508 It makes sense to use this format only if the format string also
1509 contains the @code{%y} format.
1510
1511 @item %EC
1512 The locale's representation of the period.
1513
1514 Unlike @code{%C} it sometimes makes sense to use this format since some
1515 cultures represent years relative to the beginning of eras instead of
1516 using the Gregorian years.
1517
1518 @item %d
1519 @item %e
1520 The day of the month as a decimal number (range @code{1} through @code{31}).
1521 Leading zeroes are permitted but not required.
1522
1523 @item %Od
1524 @itemx %Oe
1525 Same as @code{%d} but using the locale's alternative numeric symbols.
1526
1527 Leading zeroes are permitted but not required.
1528
1529 @item %D
1530 Equivalent to @code{%m/%d/%y}.
1531
1532 @item %F
1533 Equivalent to @code{%Y-%m-%d}, which is the @w{ISO 8601} date
1534 format.
1535
1536 This is a GNU extension following an @w{ISO C99} extension to
1537 @code{strftime}.
1538
1539 @item %g
1540 The year corresponding to the ISO week number, but without the century
1541 (range @code{00} through @code{99}).
1542
1543 @emph{Note:} Currently, this is not fully implemented. The format is
1544 recognized, input is consumed but no field in @var{tm} is set.
1545
1546 This format is a GNU extension following a GNU extension of @code{strftime}.
1547
1548 @item %G
1549 The year corresponding to the ISO week number.
1550
1551 @emph{Note:} Currently, this is not fully implemented. The format is
1552 recognized, input is consumed but no field in @var{tm} is set.
1553
1554 This format is a GNU extension following a GNU extension of @code{strftime}.
1555
1556 @item %H
1557 @itemx %k
1558 The hour as a decimal number, using a 24-hour clock (range @code{00} through
1559 @code{23}).
1560
1561 @code{%k} is a GNU extension following a GNU extension of @code{strftime}.
1562
1563 @item %OH
1564 Same as @code{%H} but using the locale's alternative numeric symbols.
1565
1566 @item %I
1567 @itemx %l
1568 The hour as a decimal number, using a 12-hour clock (range @code{01} through
1569 @code{12}).
1570
1571 @code{%l} is a GNU extension following a GNU extension of @code{strftime}.
1572
1573 @item %OI
1574 Same as @code{%I} but using the locale's alternative numeric symbols.
1575
1576 @item %j
1577 The day of the year as a decimal number (range @code{1} through @code{366}).
1578
1579 Leading zeroes are permitted but not required.
1580
1581 @item %m
1582 The month as a decimal number (range @code{1} through @code{12}).
1583
1584 Leading zeroes are permitted but not required.
1585
1586 @item %Om
1587 Same as @code{%m} but using the locale's alternative numeric symbols.
1588
1589 @item %M
1590 The minute as a decimal number (range @code{0} through @code{59}).
1591
1592 Leading zeroes are permitted but not required.
1593
1594 @item %OM
1595 Same as @code{%M} but using the locale's alternative numeric symbols.
1596
1597 @item %n
1598 @itemx %t
1599 Matches any white space.
1600
1601 @item %p
1602 @item %P
1603 The locale-dependent equivalent to @samp{AM} or @samp{PM}.
1604
1605 This format is not useful unless @code{%I} or @code{%l} is also used.
1606 Another complication is that the locale might not define these values at
1607 all and therefore the conversion fails.
1608
1609 @code{%P} is a GNU extension following a GNU extension to @code{strftime}.
1610
1611 @item %r
1612 The complete time using the AM/PM format of the current locale.
1613
1614 A complication is that the locale might not define this format at all
1615 and therefore the conversion fails.
1616
1617 @item %R
1618 The hour and minute in decimal numbers using the format @code{%H:%M}.
1619
1620 @code{%R} is a GNU extension following a GNU extension to @code{strftime}.
1621
1622 @item %s
1623 The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
1624 Leap seconds are not counted unless leap second support is available.
1625
1626 @code{%s} is a GNU extension following a GNU extension to @code{strftime}.
1627
1628 @item %S
1629 The seconds as a decimal number (range @code{0} through @code{60}).
1630
1631 Leading zeroes are permitted but not required.
1632
1633 @strong{NB:} The Unix specification says the upper bound on this value
1634 is @code{61}, a result of a decision to allow double leap seconds. You
1635 will not see the value @code{61} because no minute has more than one
1636 leap second, but the myth persists.
1637
1638 @item %OS
1639 Same as @code{%S} but using the locale's alternative numeric symbols.
1640
1641 @item %T
1642 Equivalent to the use of @code{%H:%M:%S} in this place.
1643
1644 @item %u
1645 The day of the week as a decimal number (range @code{1} through
1646 @code{7}), Monday being @code{1}.
1647
1648 Leading zeroes are permitted but not required.
1649
1650 @emph{Note:} Currently, this is not fully implemented. The format is
1651 recognized, input is consumed but no field in @var{tm} is set.
1652
1653 @item %U
1654 The week number of the current year as a decimal number (range @code{0}
1655 through @code{53}).
1656
1657 Leading zeroes are permitted but not required.
1658
1659 @item %OU
1660 Same as @code{%U} but using the locale's alternative numeric symbols.
1661
1662 @item %V
1663 The @w{ISO 8601:1988} week number as a decimal number (range @code{1}
1664 through @code{53}).
1665
1666 Leading zeroes are permitted but not required.
1667
1668 @emph{Note:} Currently, this is not fully implemented. The format is
1669 recognized, input is consumed but no field in @var{tm} is set.
1670
1671 @item %w
1672 The day of the week as a decimal number (range @code{0} through
1673 @code{6}), Sunday being @code{0}.
1674
1675 Leading zeroes are permitted but not required.
1676
1677 @emph{Note:} Currently, this is not fully implemented. The format is
1678 recognized, input is consumed but no field in @var{tm} is set.
1679
1680 @item %Ow
1681 Same as @code{%w} but using the locale's alternative numeric symbols.
1682
1683 @item %W
1684 The week number of the current year as a decimal number (range @code{0}
1685 through @code{53}).
1686
1687 Leading zeroes are permitted but not required.
1688
1689 @emph{Note:} Currently, this is not fully implemented. The format is
1690 recognized, input is consumed but no field in @var{tm} is set.
1691
1692 @item %OW
1693 Same as @code{%W} but using the locale's alternative numeric symbols.
1694
1695 @item %x
1696 The date using the locale's date format.
1697
1698 @item %Ex
1699 Like @code{%x} but the locale's alternative data representation is used.
1700
1701 @item %X
1702 The time using the locale's time format.
1703
1704 @item %EX
1705 Like @code{%X} but the locale's alternative time representation is used.
1706
1707 @item %y
1708 The year without a century as a decimal number (range @code{0} through
1709 @code{99}).
1710
1711 Leading zeroes are permitted but not required.
1712
1713 Note that it is questionable to use this format without
1714 the @code{%C} format. The @code{strptime} function does regard input
1715 values in the range @math{68} to @math{99} as the years @math{1969} to
1716 @math{1999} and the values @math{0} to @math{68} as the years
1717 @math{2000} to @math{2068}. But maybe this heuristic fails for some
1718 input data.
1719
1720 Therefore it is best to avoid @code{%y} completely and use @code{%Y}
1721 instead.
1722
1723 @item %Ey
1724 The offset from @code{%EC} in the locale's alternative representation.
1725
1726 @item %Oy
1727 The offset of the year (from @code{%C}) using the locale's alternative
1728 numeric symbols.
1729
1730 @item %Y
1731 The year as a decimal number, using the Gregorian calendar.
1732
1733 @item %EY
1734 The full alternative year representation.
1735
1736 @item %z
1737 The offset from GMT in @w{ISO 8601}/RFC822 format.
1738
1739 @item %Z
1740 The timezone name.
1741
1742 @emph{Note:} Currently, this is not fully implemented. The format is
1743 recognized, input is consumed but no field in @var{tm} is set.
1744
1745 @item %%
1746 A literal @samp{%} character.
1747 @end table
1748
1749 All other characters in the format string must have a matching character
1750 in the input string. Exceptions are white spaces in the input string
1751 which can match zero or more whitespace characters in the format string.
1752
1753 @strong{Portability Note:} The XPG standard advises applications to use
1754 at least one whitespace character (as specified by @code{isspace}) or
1755 other non-alphanumeric characters between any two conversion
1756 specifications. @Theglibc{} does not have this limitation but
1757 other libraries might have trouble parsing formats like
1758 @code{"%d%m%Y%H%M%S"}.
1759
1760 The @code{strptime} function processes the input string from right to
1761 left. Each of the three possible input elements (white space, literal,
1762 or format) are handled one after the other. If the input cannot be
1763 matched to the format string the function stops. The remainder of the
1764 format and input strings are not processed.
1765
1766 The function returns a pointer to the first character it was unable to
1767 process. If the input string contains more characters than required by
1768 the format string the return value points right after the last consumed
1769 input character. If the whole input string is consumed the return value
1770 points to the @code{NULL} byte at the end of the string. If an error
1771 occurs, i.e., @code{strptime} fails to match all of the format string,
1772 the function returns @code{NULL}.
1773 @end deftypefun
1774
1775 The specification of the function in the XPG standard is rather vague,
1776 leaving out a few important pieces of information. Most importantly, it
1777 does not specify what happens to those elements of @var{tm} which are
1778 not directly initialized by the different formats. The
1779 implementations on different Unix systems vary here.
1780
1781 The @glibcadj{} implementation does not touch those fields which are not
1782 directly initialized. Exceptions are the @code{tm_wday} and
1783 @code{tm_yday} elements, which are recomputed if any of the year, month,
1784 or date elements changed. This has two implications:
1785
1786 @itemize @bullet
1787 @item
1788 Before calling the @code{strptime} function for a new input string, you
1789 should prepare the @var{tm} structure you pass. Normally this will mean
1790 initializing all values are to zero. Alternatively, you can set all
1791 fields to values like @code{INT_MAX}, allowing you to determine which
1792 elements were set by the function call. Zero does not work here since
1793 it is a valid value for many of the fields.
1794
1795 Careful initialization is necessary if you want to find out whether a
1796 certain field in @var{tm} was initialized by the function call.
1797
1798 @item
1799 You can construct a @code{struct tm} value with several consecutive
1800 @code{strptime} calls. A useful application of this is e.g. the parsing
1801 of two separate strings, one containing date information and the other
1802 time information. By parsing one after the other without clearing the
1803 structure in-between, you can construct a complete broken-down time.
1804 @end itemize
1805
1806 The following example shows a function which parses a string which is
1807 contains the date information in either US style or @w{ISO 8601} form:
1808
1809 @smallexample
1810 const char *
1811 parse_date (const char *input, struct tm *tm)
1812 @{
1813 const char *cp;
1814
1815 /* @r{First clear the result structure.} */
1816 memset (tm, '\0', sizeof (*tm));
1817
1818 /* @r{Try the ISO format first.} */
1819 cp = strptime (input, "%F", tm);
1820 if (cp == NULL)
1821 @{
1822 /* @r{Does not match. Try the US form.} */
1823 cp = strptime (input, "%D", tm);
1824 @}
1825
1826 return cp;
1827 @}
1828 @end smallexample
1829
1830 @node General Time String Parsing
1831 @subsubsection A More User-friendly Way to Parse Times and Dates
1832
1833 The Unix standard defines another function for parsing date strings.
1834 The interface is weird, but if the function happens to suit your
1835 application it is just fine. It is problematic to use this function
1836 in multi-threaded programs or libraries, since it returns a pointer to
1837 a static variable, and uses a global variable and global state (an
1838 environment variable).
1839
1840 @comment time.h
1841 @comment Unix98
1842 @defvar getdate_err
1843 This variable of type @code{int} contains the error code of the last
1844 unsuccessful call to @code{getdate}. Defined values are:
1845
1846 @table @math
1847 @item 1
1848 The environment variable @code{DATEMSK} is not defined or null.
1849 @item 2
1850 The template file denoted by the @code{DATEMSK} environment variable
1851 cannot be opened.
1852 @item 3
1853 Information about the template file cannot retrieved.
1854 @item 4
1855 The template file is not a regular file.
1856 @item 5
1857 An I/O error occurred while reading the template file.
1858 @item 6
1859 Not enough memory available to execute the function.
1860 @item 7
1861 The template file contains no matching template.
1862 @item 8
1863 The input date is invalid, but would match a template otherwise. This
1864 includes dates like February 31st, and dates which cannot be represented
1865 in a @code{time_t} variable.
1866 @end table
1867 @end defvar
1868
1869 @comment time.h
1870 @comment Unix98
1871 @deftypefun {struct tm *} getdate (const char *@var{string})
1872 The interface to @code{getdate} is the simplest possible for a function
1873 to parse a string and return the value. @var{string} is the input
1874 string and the result is returned in a statically-allocated variable.
1875
1876 The details about how the string is processed are hidden from the user.
1877 In fact, they can be outside the control of the program. Which formats
1878 are recognized is controlled by the file named by the environment
1879 variable @code{DATEMSK}. This file should contain
1880 lines of valid format strings which could be passed to @code{strptime}.
1881
1882 The @code{getdate} function reads these format strings one after the
1883 other and tries to match the input string. The first line which
1884 completely matches the input string is used.
1885
1886 Elements not initialized through the format string retain the values
1887 present at the time of the @code{getdate} function call.
1888
1889 The formats recognized by @code{getdate} are the same as for
1890 @code{strptime}. See above for an explanation. There are only a few
1891 extensions to the @code{strptime} behavior:
1892
1893 @itemize @bullet
1894 @item
1895 If the @code{%Z} format is given the broken-down time is based on the
1896 current time of the timezone matched, not of the current timezone of the
1897 runtime environment.
1898
1899 @emph{Note}: This is not implemented (currently). The problem is that
1900 timezone names are not unique. If a fixed timezone is assumed for a
1901 given string (say @code{EST} meaning US East Coast time), then uses for
1902 countries other than the USA will fail. So far we have found no good
1903 solution to this.
1904
1905 @item
1906 If only the weekday is specified the selected day depends on the current
1907 date. If the current weekday is greater or equal to the @code{tm_wday}
1908 value the current week's day is chosen, otherwise the day next week is chosen.
1909
1910 @item
1911 A similar heuristic is used when only the month is given and not the
1912 year. If the month is greater than or equal to the current month, then
1913 the current year is used. Otherwise it wraps to next year. The first
1914 day of the month is assumed if one is not explicitly specified.
1915
1916 @item
1917 The current hour, minute, and second are used if the appropriate value is
1918 not set through the format.
1919
1920 @item
1921 If no date is given tomorrow's date is used if the time is
1922 smaller than the current time. Otherwise today's date is taken.
1923 @end itemize
1924
1925 It should be noted that the format in the template file need not only
1926 contain format elements. The following is a list of possible format
1927 strings (taken from the Unix standard):
1928
1929 @smallexample
1930 %m
1931 %A %B %d, %Y %H:%M:%S
1932 %A
1933 %B
1934 %m/%d/%y %I %p
1935 %d,%m,%Y %H:%M
1936 at %A the %dst of %B in %Y
1937 run job at %I %p,%B %dnd
1938 %A den %d. %B %Y %H.%M Uhr
1939 @end smallexample
1940
1941 As you can see, the template list can contain very specific strings like
1942 @code{run job at %I %p,%B %dnd}. Using the above list of templates and
1943 assuming the current time is Mon Sep 22 12:19:47 EDT 1986 we can obtain the
1944 following results for the given input.
1945
1946 @multitable {xxxxxxxxxxxx} {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
1947 @item Input @tab Match @tab Result
1948 @item Mon @tab %a @tab Mon Sep 22 12:19:47 EDT 1986
1949 @item Sun @tab %a @tab Sun Sep 28 12:19:47 EDT 1986
1950 @item Fri @tab %a @tab Fri Sep 26 12:19:47 EDT 1986
1951 @item September @tab %B @tab Mon Sep 1 12:19:47 EDT 1986
1952 @item January @tab %B @tab Thu Jan 1 12:19:47 EST 1987
1953 @item December @tab %B @tab Mon Dec 1 12:19:47 EST 1986
1954 @item Sep Mon @tab %b %a @tab Mon Sep 1 12:19:47 EDT 1986
1955 @item Jan Fri @tab %b %a @tab Fri Jan 2 12:19:47 EST 1987
1956 @item Dec Mon @tab %b %a @tab Mon Dec 1 12:19:47 EST 1986
1957 @item Jan Wed 1989 @tab %b %a %Y @tab Wed Jan 4 12:19:47 EST 1989
1958 @item Fri 9 @tab %a %H @tab Fri Sep 26 09:00:00 EDT 1986
1959 @item Feb 10:30 @tab %b %H:%S @tab Sun Feb 1 10:00:30 EST 1987
1960 @item 10:30 @tab %H:%M @tab Tue Sep 23 10:30:00 EDT 1986
1961 @item 13:30 @tab %H:%M @tab Mon Sep 22 13:30:00 EDT 1986
1962 @end multitable
1963
1964 The return value of the function is a pointer to a static variable of
1965 type @w{@code{struct tm}}, or a null pointer if an error occurred. The
1966 result is only valid until the next @code{getdate} call, making this
1967 function unusable in multi-threaded applications.
1968
1969 The @code{errno} variable is @emph{not} changed. Error conditions are
1970 stored in the global variable @code{getdate_err}. See the
1971 description above for a list of the possible error values.
1972
1973 @emph{Warning:} The @code{getdate} function should @emph{never} be
1974 used in SUID-programs. The reason is obvious: using the
1975 @code{DATEMSK} environment variable you can get the function to open
1976 any arbitrary file and chances are high that with some bogus input
1977 (such as a binary file) the program will crash.
1978 @end deftypefun
1979
1980 @comment time.h
1981 @comment GNU
1982 @deftypefun int getdate_r (const char *@var{string}, struct tm *@var{tp})
1983 The @code{getdate_r} function is the reentrant counterpart of
1984 @code{getdate}. It does not use the global variable @code{getdate_err}
1985 to signal an error, but instead returns an error code. The same error
1986 codes as described in the @code{getdate_err} documentation above are
1987 used, with 0 meaning success.
1988
1989 Moreover, @code{getdate_r} stores the broken-down time in the variable
1990 of type @code{struct tm} pointed to by the second argument, rather than
1991 in a static variable.
1992
1993 This function is not defined in the Unix standard. Nevertheless it is
1994 available on some other Unix systems as well.
1995
1996 The warning against using @code{getdate} in SUID-programs applies to
1997 @code{getdate_r} as well.
1998 @end deftypefun
1999
2000 @node TZ Variable
2001 @subsection Specifying the Time Zone with @code{TZ}
2002
2003 In POSIX systems, a user can specify the time zone by means of the
2004 @code{TZ} environment variable. For information about how to set
2005 environment variables, see @ref{Environment Variables}. The functions
2006 for accessing the time zone are declared in @file{time.h}.
2007 @pindex time.h
2008 @cindex time zone
2009
2010 You should not normally need to set @code{TZ}. If the system is
2011 configured properly, the default time zone will be correct. You might
2012 set @code{TZ} if you are using a computer over a network from a
2013 different time zone, and would like times reported to you in the time
2014 zone local to you, rather than what is local to the computer.
2015
2016 In POSIX.1 systems the value of the @code{TZ} variable can be in one of
2017 three formats. With @theglibc{}, the most common format is the
2018 last one, which can specify a selection from a large database of time
2019 zone information for many regions of the world. The first two formats
2020 are used to describe the time zone information directly, which is both
2021 more cumbersome and less precise. But the POSIX.1 standard only
2022 specifies the details of the first two formats, so it is good to be
2023 familiar with them in case you come across a POSIX.1 system that doesn't
2024 support a time zone information database.
2025
2026 The first format is used when there is no Daylight Saving Time (or
2027 summer time) in the local time zone:
2028
2029 @smallexample
2030 @r{@var{std} @var{offset}}
2031 @end smallexample
2032
2033 The @var{std} string specifies the name of the time zone. It must be
2034 three or more characters long and must not contain a leading colon,
2035 embedded digits, commas, nor plus and minus signs. There is no space
2036 character separating the time zone name from the @var{offset}, so these
2037 restrictions are necessary to parse the specification correctly.
2038
2039 The @var{offset} specifies the time value you must add to the local time
2040 to get a Coordinated Universal Time value. It has syntax like
2041 [@code{+}|@code{-}]@var{hh}[@code{:}@var{mm}[@code{:}@var{ss}]]. This
2042 is positive if the local time zone is west of the Prime Meridian and
2043 negative if it is east. The hour must be between @code{0} and
2044 @code{23}, and the minute and seconds between @code{0} and @code{59}.
2045
2046 For example, here is how we would specify Eastern Standard Time, but
2047 without any Daylight Saving Time alternative:
2048
2049 @smallexample
2050 EST+5
2051 @end smallexample
2052
2053 The second format is used when there is Daylight Saving Time:
2054
2055 @smallexample
2056 @r{@var{std} @var{offset} @var{dst} [@var{offset}]@code{,}@var{start}[@code{/}@var{time}]@code{,}@var{end}[@code{/}@var{time}]}
2057 @end smallexample
2058
2059 The initial @var{std} and @var{offset} specify the standard time zone, as
2060 described above. The @var{dst} string and @var{offset} specify the name
2061 and offset for the corresponding Daylight Saving Time zone; if the
2062 @var{offset} is omitted, it defaults to one hour ahead of standard time.
2063
2064 The remainder of the specification describes when Daylight Saving Time is
2065 in effect. The @var{start} field is when Daylight Saving Time goes into
2066 effect and the @var{end} field is when the change is made back to standard
2067 time. The following formats are recognized for these fields:
2068
2069 @table @code
2070 @item J@var{n}
2071 This specifies the Julian day, with @var{n} between @code{1} and @code{365}.
2072 February 29 is never counted, even in leap years.
2073
2074 @item @var{n}
2075 This specifies the Julian day, with @var{n} between @code{0} and @code{365}.
2076 February 29 is counted in leap years.
2077
2078 @item M@var{m}.@var{w}.@var{d}
2079 This specifies day @var{d} of week @var{w} of month @var{m}. The day
2080 @var{d} must be between @code{0} (Sunday) and @code{6}. The week
2081 @var{w} must be between @code{1} and @code{5}; week @code{1} is the
2082 first week in which day @var{d} occurs, and week @code{5} specifies the
2083 @emph{last} @var{d} day in the month. The month @var{m} should be
2084 between @code{1} and @code{12}.
2085 @end table
2086
2087 The @var{time} fields specify when, in the local time currently in
2088 effect, the change to the other time occurs. If omitted, the default is
2089 @code{02:00:00}.
2090
2091 For example, here is how you would specify the Eastern time zone in the
2092 United States, including the appropriate Daylight Saving Time and its dates
2093 of applicability. The normal offset from UTC is 5 hours; since this is
2094 west of the prime meridian, the sign is positive. Summer time begins on
2095 the first Sunday in April at 2:00am, and ends on the last Sunday in October
2096 at 2:00am.
2097
2098 @smallexample
2099 EST+5EDT,M4.1.0/2,M10.5.0/2
2100 @end smallexample
2101
2102 The schedule of Daylight Saving Time in any particular jurisdiction has
2103 changed over the years. To be strictly correct, the conversion of dates
2104 and times in the past should be based on the schedule that was in effect
2105 then. However, this format has no facilities to let you specify how the
2106 schedule has changed from year to year. The most you can do is specify
2107 one particular schedule---usually the present day schedule---and this is
2108 used to convert any date, no matter when. For precise time zone
2109 specifications, it is best to use the time zone information database
2110 (see below).
2111
2112 The third format looks like this:
2113
2114 @smallexample
2115 :@var{characters}
2116 @end smallexample
2117
2118 Each operating system interprets this format differently; in
2119 @theglibc{}, @var{characters} is the name of a file which describes the time
2120 zone.
2121
2122 @pindex /etc/localtime
2123 @pindex localtime
2124 If the @code{TZ} environment variable does not have a value, the
2125 operation chooses a time zone by default. In @theglibc{}, the
2126 default time zone is like the specification @samp{TZ=:/etc/localtime}
2127 (or @samp{TZ=:/usr/local/etc/localtime}, depending on how @theglibc{}
2128 was configured; @pxref{Installation}). Other C libraries use their own
2129 rule for choosing the default time zone, so there is little we can say
2130 about them.
2131
2132 @cindex time zone database
2133 @pindex /share/lib/zoneinfo
2134 @pindex zoneinfo
2135 If @var{characters} begins with a slash, it is an absolute file name;
2136 otherwise the library looks for the file
2137 @w{@file{/share/lib/zoneinfo/@var{characters}}}. The @file{zoneinfo}
2138 directory contains data files describing local time zones in many
2139 different parts of the world. The names represent major cities, with
2140 subdirectories for geographical areas; for example,
2141 @file{America/New_York}, @file{Europe/London}, @file{Asia/Hong_Kong}.
2142 These data files are installed by the system administrator, who also
2143 sets @file{/etc/localtime} to point to the data file for the local time
2144 zone. @Theglibc{} comes with a large database of time zone
2145 information for most regions of the world, which is maintained by a
2146 community of volunteers and put in the public domain.
2147
2148 @node Time Zone Functions
2149 @subsection Functions and Variables for Time Zones
2150
2151 @comment time.h
2152 @comment POSIX.1
2153 @deftypevar {char *} tzname [2]
2154 The array @code{tzname} contains two strings, which are the standard
2155 names of the pair of time zones (standard and Daylight
2156 Saving) that the user has selected. @code{tzname[0]} is the name of
2157 the standard time zone (for example, @code{"EST"}), and @code{tzname[1]}
2158 is the name for the time zone when Daylight Saving Time is in use (for
2159 example, @code{"EDT"}). These correspond to the @var{std} and @var{dst}
2160 strings (respectively) from the @code{TZ} environment variable. If
2161 Daylight Saving Time is never used, @code{tzname[1]} is the empty string.
2162
2163 The @code{tzname} array is initialized from the @code{TZ} environment
2164 variable whenever @code{tzset}, @code{ctime}, @code{strftime},
2165 @code{mktime}, or @code{localtime} is called. If multiple abbreviations
2166 have been used (e.g. @code{"EWT"} and @code{"EDT"} for U.S. Eastern War
2167 Time and Eastern Daylight Time), the array contains the most recent
2168 abbreviation.
2169
2170 The @code{tzname} array is required for POSIX.1 compatibility, but in
2171 GNU programs it is better to use the @code{tm_zone} member of the
2172 broken-down time structure, since @code{tm_zone} reports the correct
2173 abbreviation even when it is not the latest one.
2174
2175 Though the strings are declared as @code{char *} the user must refrain
2176 from modifying these strings. Modifying the strings will almost certainly
2177 lead to trouble.
2178
2179 @end deftypevar
2180
2181 @comment time.h
2182 @comment POSIX.1
2183 @deftypefun void tzset (void)
2184 The @code{tzset} function initializes the @code{tzname} variable from
2185 the value of the @code{TZ} environment variable. It is not usually
2186 necessary for your program to call this function, because it is called
2187 automatically when you use the other time conversion functions that
2188 depend on the time zone.
2189 @end deftypefun
2190
2191 The following variables are defined for compatibility with System V
2192 Unix. Like @code{tzname}, these variables are set by calling
2193 @code{tzset} or the other time conversion functions.
2194
2195 @comment time.h
2196 @comment SVID
2197 @deftypevar {long int} timezone
2198 This contains the difference between UTC and the latest local standard
2199 time, in seconds west of UTC. For example, in the U.S. Eastern time
2200 zone, the value is @code{5*60*60}. Unlike the @code{tm_gmtoff} member
2201 of the broken-down time structure, this value is not adjusted for
2202 daylight saving, and its sign is reversed. In GNU programs it is better
2203 to use @code{tm_gmtoff}, since it contains the correct offset even when
2204 it is not the latest one.
2205 @end deftypevar
2206
2207 @comment time.h
2208 @comment SVID
2209 @deftypevar int daylight
2210 This variable has a nonzero value if Daylight Saving Time rules apply.
2211 A nonzero value does not necessarily mean that Daylight Saving Time is
2212 now in effect; it means only that Daylight Saving Time is sometimes in
2213 effect.
2214 @end deftypevar
2215
2216 @node Time Functions Example
2217 @subsection Time Functions Example
2218
2219 Here is an example program showing the use of some of the calendar time
2220 functions.
2221
2222 @smallexample
2223 @include strftim.c.texi
2224 @end smallexample
2225
2226 It produces output like this:
2227
2228 @smallexample
2229 Wed Jul 31 13:02:36 1991
2230 Today is Wednesday, July 31.
2231 The time is 01:02 PM.
2232 @end smallexample
2233
2234
2235 @node Setting an Alarm
2236 @section Setting an Alarm
2237
2238 The @code{alarm} and @code{setitimer} functions provide a mechanism for a
2239 process to interrupt itself in the future. They do this by setting a
2240 timer; when the timer expires, the process receives a signal.
2241
2242 @cindex setting an alarm
2243 @cindex interval timer, setting
2244 @cindex alarms, setting
2245 @cindex timers, setting
2246 Each process has three independent interval timers available:
2247
2248 @itemize @bullet
2249 @item
2250 A real-time timer that counts elapsed time. This timer sends a
2251 @code{SIGALRM} signal to the process when it expires.
2252 @cindex real-time timer
2253 @cindex timer, real-time
2254
2255 @item
2256 A virtual timer that counts processor time used by the process. This timer
2257 sends a @code{SIGVTALRM} signal to the process when it expires.
2258 @cindex virtual timer
2259 @cindex timer, virtual
2260
2261 @item
2262 A profiling timer that counts both processor time used by the process,
2263 and processor time spent in system calls on behalf of the process. This
2264 timer sends a @code{SIGPROF} signal to the process when it expires.
2265 @cindex profiling timer
2266 @cindex timer, profiling
2267
2268 This timer is useful for profiling in interpreters. The interval timer
2269 mechanism does not have the fine granularity necessary for profiling
2270 native code.
2271 @c @xref{profil} !!!
2272 @end itemize
2273
2274 You can only have one timer of each kind set at any given time. If you
2275 set a timer that has not yet expired, that timer is simply reset to the
2276 new value.
2277
2278 You should establish a handler for the appropriate alarm signal using
2279 @code{signal} or @code{sigaction} before issuing a call to
2280 @code{setitimer} or @code{alarm}. Otherwise, an unusual chain of events
2281 could cause the timer to expire before your program establishes the
2282 handler. In this case it would be terminated, since termination is the
2283 default action for the alarm signals. @xref{Signal Handling}.
2284
2285 To be able to use the alarm function to interrupt a system call which
2286 might block otherwise indefinitely it is important to @emph{not} set the
2287 @code{SA_RESTART} flag when registering the signal handler using
2288 @code{sigaction}. When not using @code{sigaction} things get even
2289 uglier: the @code{signal} function has to fixed semantics with respect
2290 to restarts. The BSD semantics for this function is to set the flag.
2291 Therefore, if @code{sigaction} for whatever reason cannot be used, it is
2292 necessary to use @code{sysv_signal} and not @code{signal}.
2293
2294 The @code{setitimer} function is the primary means for setting an alarm.
2295 This facility is declared in the header file @file{sys/time.h}. The
2296 @code{alarm} function, declared in @file{unistd.h}, provides a somewhat
2297 simpler interface for setting the real-time timer.
2298 @pindex unistd.h
2299 @pindex sys/time.h
2300
2301 @comment sys/time.h
2302 @comment BSD
2303 @deftp {Data Type} {struct itimerval}
2304 This structure is used to specify when a timer should expire. It contains
2305 the following members:
2306 @table @code
2307 @item struct timeval it_interval
2308 This is the period between successive timer interrupts. If zero, the
2309 alarm will only be sent once.
2310
2311 @item struct timeval it_value
2312 This is the period between now and the first timer interrupt. If zero,
2313 the alarm is disabled.
2314 @end table
2315
2316 The @code{struct timeval} data type is described in @ref{Elapsed Time}.
2317 @end deftp
2318
2319 @comment sys/time.h
2320 @comment BSD
2321 @deftypefun int setitimer (int @var{which}, const struct itimerval *@var{new}, struct itimerval *@var{old})
2322 The @code{setitimer} function sets the timer specified by @var{which}
2323 according to @var{new}. The @var{which} argument can have a value of
2324 @code{ITIMER_REAL}, @code{ITIMER_VIRTUAL}, or @code{ITIMER_PROF}.
2325
2326 If @var{old} is not a null pointer, @code{setitimer} returns information
2327 about any previous unexpired timer of the same kind in the structure it
2328 points to.
2329
2330 The return value is @code{0} on success and @code{-1} on failure. The
2331 following @code{errno} error conditions are defined for this function:
2332
2333 @table @code
2334 @item EINVAL
2335 The timer period is too large.
2336 @end table
2337 @end deftypefun
2338
2339 @comment sys/time.h
2340 @comment BSD
2341 @deftypefun int getitimer (int @var{which}, struct itimerval *@var{old})
2342 The @code{getitimer} function stores information about the timer specified
2343 by @var{which} in the structure pointed at by @var{old}.
2344
2345 The return value and error conditions are the same as for @code{setitimer}.
2346 @end deftypefun
2347
2348 @comment sys/time.h
2349 @comment BSD
2350 @vtable @code
2351 @item ITIMER_REAL
2352 This constant can be used as the @var{which} argument to the
2353 @code{setitimer} and @code{getitimer} functions to specify the real-time
2354 timer.
2355
2356 @comment sys/time.h
2357 @comment BSD
2358 @item ITIMER_VIRTUAL
2359 This constant can be used as the @var{which} argument to the
2360 @code{setitimer} and @code{getitimer} functions to specify the virtual
2361 timer.
2362
2363 @comment sys/time.h
2364 @comment BSD
2365 @item ITIMER_PROF
2366 This constant can be used as the @var{which} argument to the
2367 @code{setitimer} and @code{getitimer} functions to specify the profiling
2368 timer.
2369 @end vtable
2370
2371 @comment unistd.h
2372 @comment POSIX.1
2373 @deftypefun {unsigned int} alarm (unsigned int @var{seconds})
2374 The @code{alarm} function sets the real-time timer to expire in
2375 @var{seconds} seconds. If you want to cancel any existing alarm, you
2376 can do this by calling @code{alarm} with a @var{seconds} argument of
2377 zero.
2378
2379 The return value indicates how many seconds remain before the previous
2380 alarm would have been sent. If there is no previous alarm, @code{alarm}
2381 returns zero.
2382 @end deftypefun
2383
2384 The @code{alarm} function could be defined in terms of @code{setitimer}
2385 like this:
2386
2387 @smallexample
2388 unsigned int
2389 alarm (unsigned int seconds)
2390 @{
2391 struct itimerval old, new;
2392 new.it_interval.tv_usec = 0;
2393 new.it_interval.tv_sec = 0;
2394 new.it_value.tv_usec = 0;
2395 new.it_value.tv_sec = (long int) seconds;
2396 if (setitimer (ITIMER_REAL, &new, &old) < 0)
2397 return 0;
2398 else
2399 return old.it_value.tv_sec;
2400 @}
2401 @end smallexample
2402
2403 There is an example showing the use of the @code{alarm} function in
2404 @ref{Handler Returns}.
2405
2406 If you simply want your process to wait for a given number of seconds,
2407 you should use the @code{sleep} function. @xref{Sleeping}.
2408
2409 You shouldn't count on the signal arriving precisely when the timer
2410 expires. In a multiprocessing environment there is typically some
2411 amount of delay involved.
2412
2413 @strong{Portability Note:} The @code{setitimer} and @code{getitimer}
2414 functions are derived from BSD Unix, while the @code{alarm} function is
2415 specified by the POSIX.1 standard. @code{setitimer} is more powerful than
2416 @code{alarm}, but @code{alarm} is more widely used.
2417
2418 @node Sleeping
2419 @section Sleeping
2420
2421 The function @code{sleep} gives a simple way to make the program wait
2422 for a short interval. If your program doesn't use signals (except to
2423 terminate), then you can expect @code{sleep} to wait reliably throughout
2424 the specified interval. Otherwise, @code{sleep} can return sooner if a
2425 signal arrives; if you want to wait for a given interval regardless of
2426 signals, use @code{select} (@pxref{Waiting for I/O}) and don't specify
2427 any descriptors to wait for.
2428 @c !!! select can get EINTR; using SA_RESTART makes sleep win too.
2429
2430 @comment unistd.h
2431 @comment POSIX.1
2432 @deftypefun {unsigned int} sleep (unsigned int @var{seconds})
2433 The @code{sleep} function waits for @var{seconds} or until a signal
2434 is delivered, whichever happens first.
2435
2436 If @code{sleep} function returns because the requested interval is over,
2437 it returns a value of zero. If it returns because of delivery of a
2438 signal, its return value is the remaining time in the sleep interval.
2439
2440 The @code{sleep} function is declared in @file{unistd.h}.
2441 @end deftypefun
2442
2443 Resist the temptation to implement a sleep for a fixed amount of time by
2444 using the return value of @code{sleep}, when nonzero, to call
2445 @code{sleep} again. This will work with a certain amount of accuracy as
2446 long as signals arrive infrequently. But each signal can cause the
2447 eventual wakeup time to be off by an additional second or so. Suppose a
2448 few signals happen to arrive in rapid succession by bad luck---there is
2449 no limit on how much this could shorten or lengthen the wait.
2450
2451 Instead, compute the calendar time at which the program should stop
2452 waiting, and keep trying to wait until that calendar time. This won't
2453 be off by more than a second. With just a little more work, you can use
2454 @code{select} and make the waiting period quite accurate. (Of course,
2455 heavy system load can cause additional unavoidable delays---unless the
2456 machine is dedicated to one application, there is no way you can avoid
2457 this.)
2458
2459 On some systems, @code{sleep} can do strange things if your program uses
2460 @code{SIGALRM} explicitly. Even if @code{SIGALRM} signals are being
2461 ignored or blocked when @code{sleep} is called, @code{sleep} might
2462 return prematurely on delivery of a @code{SIGALRM} signal. If you have
2463 established a handler for @code{SIGALRM} signals and a @code{SIGALRM}
2464 signal is delivered while the process is sleeping, the action taken
2465 might be just to cause @code{sleep} to return instead of invoking your
2466 handler. And, if @code{sleep} is interrupted by delivery of a signal
2467 whose handler requests an alarm or alters the handling of @code{SIGALRM},
2468 this handler and @code{sleep} will interfere.
2469
2470 On @gnusystems{}, it is safe to use @code{sleep} and @code{SIGALRM} in
2471 the same program, because @code{sleep} does not work by means of
2472 @code{SIGALRM}.
2473
2474 @comment time.h
2475 @comment POSIX.1
2476 @deftypefun int nanosleep (const struct timespec *@var{requested_time}, struct timespec *@var{remaining})
2477 If resolution to seconds is not enough the @code{nanosleep} function can
2478 be used. As the name suggests the sleep interval can be specified in
2479 nanoseconds. The actual elapsed time of the sleep interval might be
2480 longer since the system rounds the elapsed time you request up to the
2481 next integer multiple of the actual resolution the system can deliver.
2482
2483 *@code{requested_time} is the elapsed time of the interval you want to
2484 sleep.
2485
2486 The function returns as *@code{remaining} the elapsed time left in the
2487 interval for which you requested to sleep. If the interval completed
2488 without getting interrupted by a signal, this is zero.
2489
2490 @code{struct timespec} is described in @xref{Elapsed Time}.
2491
2492 If the function returns because the interval is over the return value is
2493 zero. If the function returns @math{-1} the global variable @var{errno}
2494 is set to the following values:
2495
2496 @table @code
2497 @item EINTR
2498 The call was interrupted because a signal was delivered to the thread.
2499 If the @var{remaining} parameter is not the null pointer the structure
2500 pointed to by @var{remaining} is updated to contain the remaining
2501 elapsed time.
2502
2503 @item EINVAL
2504 The nanosecond value in the @var{requested_time} parameter contains an
2505 illegal value. Either the value is negative or greater than or equal to
2506 1000 million.
2507 @end table
2508
2509 This function is a cancellation point in multi-threaded programs. This
2510 is a problem if the thread allocates some resources (like memory, file
2511 descriptors, semaphores or whatever) at the time @code{nanosleep} is
2512 called. If the thread gets canceled these resources stay allocated
2513 until the program ends. To avoid this calls to @code{nanosleep} should
2514 be protected using cancellation handlers.
2515 @c ref pthread_cleanup_push / pthread_cleanup_pop
2516
2517 The @code{nanosleep} function is declared in @file{time.h}.
2518 @end deftypefun
This page took 0.151672 seconds and 5 git commands to generate.