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