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