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