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