1 @node Date and Time, Resource Usage And Limitation, Arithmetic, Top
2 @c %MENU% Functions for getting the date and time and formatting them nicely
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.
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.
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.
29 A @dfn{calendar time} is a point in the time continuum, for example
30 November 4, 1990, at 18:02.5 UTC. Sometimes this is called ``absolute
34 We don't speak of a ``date'', because that is inherent in a calendar
38 An @dfn{interval} is a contiguous part of the time continuum between two
39 calendar times, for example the hour between 9:00 and 10:00 on July 4,
43 An @dfn{elapsed time} is the length of an interval, for example, 35
44 minutes. People sometimes sloppily use the word ``interval'' to refer
45 to the elapsed time of some interval.
49 An @dfn{amount of time} is a sum of elapsed times, which need not be of
50 any specific intervals. For example, the amount of time it takes to
51 read a book might be 9 hours, independently of when and in how many
54 A @dfn{period} is the elapsed time of an interval between two events,
55 especially when they are part of a sequence of regularly repeating
57 @cindex period of time
59 A @dfn{simple calendar time} is a calendar time represented as an
60 elapsed time since a fixed, implementation-specific calendar time
61 called the @dfn{epoch}. This representation is convenient for doing
62 calculations on calendar times, such as finding the elapsed time
63 between two calendar times. Simple calendar times are independent of
64 time zone; they represent the same instant in time regardless of where
65 on the globe the computer is.
67 POSIX says that simple calendar times do not include leap seconds, but
68 some (otherwise POSIX-conformant) systems can be configured to include
69 leap seconds in simple calendar times.
73 @cindex simple calendar time
74 @cindex calendar time, simple
77 A @dfn{broken-down time} is a calendar time represented by its
78 components in the Gregorian calendar: year, month, day, hour, minute,
79 and second. A broken-down time value is relative to a specific time
80 zone, and so it is also sometimes called a @dfn{local time}.
81 Broken-down times are most useful for input and output, as they are
82 easier for people to understand, but more difficult to calculate with.
83 @cindex broken-down time
85 @cindex Gregorian calendar
86 @cindex calendar, Gregorian
88 @dfn{CPU time} measures the amount of time that a single process has
89 actively used a CPU to perform computations. It does not include the
90 time that process has spent waiting for external events. The system
91 tracks the CPU time used by each process separately.
94 @dfn{Processor time} measures the amount of time @emph{any} CPU has
95 been in use by @emph{any} process. It is a basic system resource,
96 since there's a limit to how much can exist in any given interval (the
97 elapsed time of the interval times the number of CPUs in the computer)
99 People often call this CPU time, but we reserve the latter term in
100 this manual for the definition above.
101 @cindex processor time
106 ISO C and POSIX define several data types for representing elapsed
107 times, simple calendar times, and broken-down times.
109 @deftp {Data Type} clock_t
110 @standards{ISO, time.h}
111 @code{clock_t} is used to measure processor and CPU time.
112 It may be an integer or a floating-point type.
113 Its values are counts of @dfn{clock ticks} since some arbitrary event
115 The number of clock ticks per second is system-specific.
116 @xref{Processor And CPU Time}, for further detail.
121 @deftp {Data Type} time_t
122 @standards{ISO, time.h}
123 @code{time_t} is the simplest data type used to represent simple
126 In ISO C, @code{time_t} can be either an integer or a floating-point
127 type, and the meaning of @code{time_t} values is not specified. The
128 only things a strictly conforming program can do with @code{time_t}
129 values are: pass them to @code{difftime} to get the elapsed time
130 between two simple calendar times (@pxref{Calculating Elapsed Time}),
131 and pass them to the functions that convert them to broken-down time
132 (@pxref{Broken-down Time}).
134 On POSIX-conformant systems, @code{time_t} is an integer type and its
135 values represent the number of seconds elapsed since the @dfn{epoch},
136 which is 00:00:00 on January 1, 1970, Coordinated Universal Time.
138 @Theglibc{} additionally guarantees that @code{time_t} is a signed
139 type, and that all of its functions operate correctly on negative
140 @code{time_t} values, which are interpreted as times before the epoch.
144 @deftp {Data Type} {struct timespec}
145 @standards{POSIX.1, time.h}
147 @code{struct timespec} represents a simple calendar time, or an
148 elapsed time, with sub-second resolution. It is declared in
149 @file{time.h} and has the following members:
153 The number of whole seconds elapsed since the epoch (for a simple
154 calendar time) or since some other starting point (for an elapsed
157 @item long int tv_nsec
158 The number of nanoseconds elapsed since the time given by the
159 @code{tv_sec} member.
161 When @code{struct timespec} values are produced by @glibcadj{}
162 functions, the value in this field will always be greater than or
163 equal to zero, and less than 1,000,000,000.
164 When @code{struct timespec} values are supplied to @glibcadj{}
165 functions, the value in this field must be in the same range.
169 @deftp {Data Type} {struct timeval}
170 @standards{BSD, sys/time.h}
172 @code{struct timeval} is an older type for representing a simple
173 calendar time, or an elapsed time, with sub-second resolution. It is
174 almost the same as @code{struct timespec}, but provides only
175 microsecond resolution. It is declared in @file{sys/time.h} and has
176 the following members:
180 The number of whole seconds elapsed since the epoch (for a simple
181 calendar time) or since some other starting point (for an elapsed
184 @item long int tv_usec
185 The number of microseconds elapsed since the time given by the
186 @code{tv_sec} member.
188 When @code{struct timeval} values are produced by @glibcadj{}
189 functions, the value in this field will always be greater than or
190 equal to zero, and less than 1,000,000.
191 When @code{struct timeval} values are supplied to @glibcadj{}
192 functions, the value in this field must be in the same range.
196 @deftp {Data Type} {struct tm}
197 @standards{ISO, time.h}
198 This is the data type used to represent a broken-down time. It has
199 separate fields for year, month, day, and so on.
200 @xref{Broken-down Time}, for further details.
203 @node Calculating Elapsed Time
204 @section Calculating Elapsed Time
206 Often, one wishes to calculate an elapsed time as the difference
207 between two simple calendar times. @Theglibc{} provides only one
208 function for this purpose.
210 @deftypefun double difftime (time_t @var{end}, time_t @var{begin})
211 @standards{ISO, time.h}
212 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
213 The @code{difftime} function returns the number of seconds of elapsed
214 time from calendar time @var{begin} to calendar time @var{end}, as
215 a value of type @code{double}.
217 On POSIX-conformant systems, the advantage of using
218 @samp{difftime (@var{end}, @var{begin})} over @samp{@var{end} - @var{begin}}
219 is that it will produce the mathematically correct result even if
220 @var{end} and @var{begin} are so far apart that a simple subtraction
221 would overflow. However, if they are so far apart that a @code{double}
222 cannot exactly represent the difference, the result will be inexact.
224 On other systems, @code{time_t} values might be encoded in a way that
225 prevents subtraction from working directly, and then @code{difftime}
226 would be the only way to compute their difference.
229 @Theglibc{} does not provide any functions for computing the
230 difference between two values of type @w{@code{struct timeval}} or
231 @w{@code{struct timespec}}. Here is the recommended way to do this
232 calculation by hand. It works even on some peculiar operating systems
233 where the @code{tv_sec} member has an unsigned type.
236 @include timeval_subtract.c.texi
239 @node Processor And CPU Time
240 @section Processor And CPU Time
242 If you're trying to optimize your program or measure its efficiency,
243 it's very useful to know how much processor time it uses. For that,
244 calendar time and elapsed times are useless because a process may spend
245 time waiting for I/O or for other processes to use the CPU. However,
246 you can get the information with the functions in this section.
248 CPU time (@pxref{Time Basics}) is represented by the data type
249 @code{clock_t}, which is a number of @dfn{clock ticks}. It gives the
250 total amount of time a process has actively used a CPU since some
251 arbitrary event. On @gnusystems{}, that event is the creation of the
252 process. While arbitrary in general, the event is always the same event
253 for any particular process, so you can always measure how much time on
254 the CPU a particular computation takes by examining the process' CPU
255 time before and after the computation.
260 On @gnulinuxhurdsystems{}, @code{clock_t} is equivalent to @code{long int} and
261 @code{CLOCKS_PER_SEC} is an integer value. But in other systems, both
262 @code{clock_t} and the macro @code{CLOCKS_PER_SEC} can be either integer
263 or floating-point types. Casting CPU time values to @code{double}, as
264 in the example above, makes sure that operations such as arithmetic and
265 printing work properly and consistently no matter what the underlying
268 Note that the clock can wrap around. On a 32bit system with
269 @code{CLOCKS_PER_SEC} set to one million this function will return the
270 same value approximately every 72 minutes.
272 For additional functions to examine a process' use of processor time,
273 and to control it, see @ref{Resource Usage And Limitation}.
277 * CPU Time:: The @code{clock} function.
278 * Processor Time:: The @code{times} function.
282 @subsection CPU Time Inquiry
284 To get a process' CPU time, you can use the @code{clock} function. This
285 facility is declared in the header file @file{time.h}.
288 In typical usage, you call the @code{clock} function at the beginning
289 and end of the interval you want to time, subtract the values, and then
290 divide by @code{CLOCKS_PER_SEC} (the number of clock ticks per second)
291 to get processor time, like this:
298 double cpu_time_used;
301 @dots{} /* @r{Do the work.} */
303 cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
307 Do not use a single CPU time as an amount of time; it doesn't work that
308 way. Either do a subtraction as shown above or query processor time
309 directly. @xref{Processor Time}.
311 Different computers and operating systems vary wildly in how they keep
312 track of CPU time. It's common for the internal processor clock
313 to have a resolution somewhere between a hundredth and millionth of a
316 @deftypevr Macro int CLOCKS_PER_SEC
317 @standards{ISO, time.h}
318 The value of this macro is the number of clock ticks per second measured
319 by the @code{clock} function. POSIX requires that this value be one
320 million independent of the actual resolution.
323 @deftypefun clock_t clock (void)
324 @standards{ISO, time.h}
325 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
326 @c On Hurd, this calls task_info twice and adds user and system time
327 @c from both basic and thread time info structs. On generic posix,
328 @c calls times and adds utime and stime. On bsd, calls getrusage and
329 @c safely converts stime and utime to clock. On linux, calls
331 This function returns the calling process' current CPU time. If the CPU
332 time is not available or cannot be represented, @code{clock} returns the
333 value @code{(clock_t)(-1)}.
338 @subsection Processor Time Inquiry
340 The @code{times} function returns information about a process'
341 consumption of processor time in a @w{@code{struct tms}} object, in
342 addition to the process' CPU time. @xref{Time Basics}. You should
343 include the header file @file{sys/times.h} to use this facility.
344 @cindex processor time
348 @deftp {Data Type} {struct tms}
349 @standards{POSIX.1, sys/times.h}
350 The @code{tms} structure is used to return information about process
351 times. It contains at least the following members:
354 @item clock_t tms_utime
355 This is the total processor time the calling process has used in
356 executing the instructions of its program.
358 @item clock_t tms_stime
359 This is the processor time the system has used on behalf of the calling
362 @item clock_t tms_cutime
363 This is the sum of the @code{tms_utime} values and the @code{tms_cutime}
364 values of all terminated child processes of the calling process, whose
365 status has been reported to the parent process by @code{wait} or
366 @code{waitpid}; see @ref{Process Completion}. In other words, it
367 represents the total processor time used in executing the instructions
368 of all the terminated child processes of the calling process, excluding
369 child processes which have not yet been reported by @code{wait} or
371 @cindex child process
373 @item clock_t tms_cstime
374 This is similar to @code{tms_cutime}, but represents the total processor
375 time the system has used on behalf of all the terminated child processes
376 of the calling process.
379 All of the times are given in numbers of clock ticks. Unlike CPU time,
380 these are the actual amounts of time; not relative to any event.
381 @xref{Creating a Process}.
384 @deftypevr Macro int CLK_TCK
385 @standards{POSIX.1, time.h}
386 This is an obsolete name for the number of clock ticks per second. Use
387 @code{sysconf (_SC_CLK_TCK)} instead.
390 @deftypefun clock_t times (struct tms *@var{buffer})
391 @standards{POSIX.1, sys/times.h}
392 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
393 @c On HURD, this calls task_info twice, for basic and thread times info,
394 @c adding user and system times into tms, and then gettimeofday, to
395 @c compute the real time. On BSD, it calls getclktck, getrusage (twice)
396 @c and time. On Linux, it's a syscall with special handling to account
397 @c for clock_t counts that look like error values.
398 The @code{times} function stores the processor time information for
399 the calling process in @var{buffer}.
401 The return value is the number of clock ticks since an arbitrary point
402 in the past, e.g. since system start-up. @code{times} returns
403 @code{(clock_t)(-1)} to indicate failure.
406 @strong{Portability Note:} The @code{clock} function described in
407 @ref{CPU Time} is specified by the @w{ISO C} standard. The
408 @code{times} function is a feature of POSIX.1. On @gnusystems{}, the
409 CPU time is defined to be equivalent to the sum of the @code{tms_utime}
410 and @code{tms_stime} fields returned by @code{times}.
413 @section Calendar Time
415 This section describes the functions for getting, setting, and
416 manipulating calendar times.
419 * Getting the Time:: Functions for finding out what time it is.
420 * Setting and Adjusting the Time::
421 Functions for setting and adjusting
423 * Broken-down Time:: Facilities for manipulating local time.
424 * Formatting Calendar Time:: Converting times to strings.
425 * Parsing Date and Time:: Convert textual time and date information back
426 into broken-down time values.
427 * TZ Variable:: How users specify the time zone.
428 * Time Zone Functions:: Functions to examine or specify the time zone.
429 * Time Functions Example:: An example program showing use of some of
433 @node Getting the Time
434 @subsection Getting the Time
436 @Theglibc{} provides several functions for getting the current
437 calendar time, with different levels of resolution.
439 @deftypefun time_t time (time_t *@var{result})
440 @standards{ISO, time.h}
441 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
442 This is the simplest function for getting the current calendar time.
443 It returns the calendar time as a value of type @code{time_t}; on
444 POSIX systems, that means it has a resolution of one second. It
445 uses the same clock as @w{@samp{clock_gettime (CLOCK_REALTIME_COARSE)}},
446 when the clock is available or @w{@samp{clock_gettime (CLOCK_REALTIME)}}
449 If the argument @var{result} is not a null pointer, the calendar time
450 value is also stored in @code{*@var{result}}.
452 This function cannot fail.
455 Some applications need more precise timekeeping than is possible with
456 a @code{time_t} alone. Some applications also need more control over
457 what is meant by ``the current time.'' For these applications, POSIX
458 provides a function @code{clock_gettime} that can retrieve the time
459 with up to nanosecond precision, from a variety of different clocks.
460 Clocks can be system-wide, measuring time the same for all processes;
461 or they can be per-process or per-thread, measuring CPU time consumed
462 by a particular process, or some other similar resource. Each clock
463 has its own resolution and epoch. You can find the resolution of a
464 clock with the function @code{clock_getres}. There is no function to
465 get the epoch for a clock; either it is fixed and documented, or the
466 clock is not meant to be used to measure absolute times.
468 @deftp {Data Type} clockid_t
469 @standards{POSIX.1, time.h}
470 The type @code{clockid_t} is used for constants that indicate which of
471 several system clocks one wishes to use.
474 All systems that support this family of functions will define at least
477 @deftypevr Macro clockid_t CLOCK_REALTIME
478 @standards{POSIX.1, time.h}
479 This clock uses the POSIX epoch, 00:00:00 on January 1, 1970, Coordinated
480 Universal Time. It is close to, but not necessarily in lock-step with, the
481 clocks of @code{time} (above) and of @code{gettimeofday} (below).
484 @cindex monotonic time
485 A second clock constant which is not universal, but still very common,
486 is for a clock measuring @dfn{monotonic time}. Monotonic time is
487 useful for measuring elapsed times, because it guarantees that those
488 measurements are not affected by changes to the system clock.
490 @deftypevr Macro clockid_t CLOCK_MONOTONIC
491 @standards{POSIX.1, time.h}
492 System-wide clock that continuously measures the advancement of
493 calendar time, ignoring discontinuous changes to the system's
494 setting for absolute calendar time.
496 The epoch for this clock is an unspecified point in the past.
497 The epoch may change if the system is rebooted or suspended.
498 Therefore, @code{CLOCK_MONOTONIC} cannot be used to measure
499 absolute time, only elapsed time.
502 Systems may support more than just these two clocks.
504 @deftypefun int clock_gettime (clockid_t @var{clock}, struct timespec *@var{ts})
505 @standards{POSIX.1, time.h}
506 Get the current time accoding to the clock identified by @var{clock},
507 storing it as seconds and nanoseconds in @code{*@var{ts}}.
508 @xref{Time Types}, for a description of @code{struct timespec}.
510 The return value is @code{0} on success and @code{-1} on failure. The
511 following @code{errno} error condition is defined for this function:
515 The clock identified by @var{clock} is not supported.
519 @code{clock_gettime} reports the time scaled to seconds and
520 nanoseconds, but the actual resolution of each clock may not be as
521 fine as one nanosecond, and may not be the same for all clocks. POSIX
522 also provides a function for finding out the actual resolution of a
525 @deftypefun int clock_getres (clockid_t @var{clock}, struct timespec *@var{res})
526 @standards{POSIX.1, time.h}
527 Get the actual resolution of the clock identified by @var{clock},
528 storing it in @code{*@var{ts}}.
530 For instance, if the clock hardware for @code{CLOCK_REALTIME}
531 uses a quartz crystal that oscillates at 32.768 kHz,
532 then its resolution would be 30.518 microseconds,
533 and @w{@samp{clock_getres (CLOCK_REALTIME, &r)}} would set
534 @code{r.tv_sec} to 0 and @code{r.tv_nsec} to 30518.
536 The return value is @code{0} on success and @code{-1} on failure. The
537 following @code{errno} error condition is defined for this function:
541 The clock identified by @var{clock} is not supported.
545 These functions, and the constants that identify particular clocks,
546 are declared in @file{time.h}.
548 @strong{Portability Note:} On some systems, including systems that use
549 older versions of @theglibc{}, programs that use @code{clock_gettime}
550 or @code{clock_setres} must be linked with the @code{-lrt} library.
551 This has not been necessary with @theglibc{} since version 2.17.
553 @Theglibc{} also provides an older, but still widely used, function
554 for getting the current time with a resolution of microseconds. This
555 function is declared in @file{sys/time.h}.
557 @deftypefun int gettimeofday (struct timeval *@var{tp}, void *@var{tzp})
558 @standards{BSD, sys/time.h}
559 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
560 Get the current calendar time, storing it as seconds and microseconds
561 in @code{*@var{tp}}. @xref{Time Types}, for a description of
562 @code{struct timeval}. The clock of @code{gettimeofday} is close to,
563 but not necessarily in lock-step with, the clocks of @code{time} and of
564 @w{@samp{clock_gettime (CLOCK_REALTIME)}} (see above).
566 On some historic systems, if @var{tzp} was not a null pointer,
567 information about a system-wide time zone would be written to
568 @code{*@var{tzp}}. This feature is obsolete and not supported on
569 @gnusystems{}. You should always supply a null pointer for this
570 argument. Instead, use the facilities described in @ref{Time Zone
571 Functions} and in @ref{Broken-down Time} for working with time zones.
573 This function cannot fail, and its return value is always @code{0}.
575 @strong{Portability Note:} As of the 2008 revision of POSIX, this
576 function is considered obsolete. @Theglibc{} will continue to provide
577 this function indefinitely, but new programs should use
578 @code{clock_gettime} instead.
581 @node Setting and Adjusting the Time
582 @subsection Setting and Adjusting the Time
584 The clock hardware inside a modern computer is quite reliable, but it
585 can still be wrong. The functions in this section allow one to set
586 the system's idea of the current calendar time, and to adjust the rate
587 at which the system counts seconds, so that the calendar time will
588 both be accurate, and remain accurate.
590 The functions in this section require special privileges to use.
591 @xref{Users and Groups}.
593 @deftypefun int clock_settime (clockid_t @var{clock}, const struct timespec *@var{ts})
594 @standards{POSIX, time.h}
595 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
596 Change the current calendar time, according to the clock identified by
597 @var{clock}, to be the simple calendar time in @code{*@var{ts}}.
599 Not all of the system's clocks can be changed. For instance, the
600 @code{CLOCK_REALTIME} clock can be changed (with the appropriate
601 privileges), but the @code{CLOCK_MONOTONIC} clock cannot.
603 Because simple calendar times are independent of time zone, this
604 function should not be used when the time zone changes (e.g.@: if the
605 computer is physically moved from one zone to another). Instead, use
606 the facilities described in @ref{Time Zone Functions}.
608 @code{clock_settime} causes the clock to jump forwards or backwards,
609 which can cause a variety of problems. Changing the
610 @code{CLOCK_REALTIME} clock with @code{clock_settime} does not affect
611 when timers expire (@pxref{Setting an Alarm}) or when sleeping
612 processes wake up (@pxref{Sleeping}), which avoids some of the
613 problems. Still, for small changes made while the system is running,
614 it is better to use @code{ntp_adjtime} (below) to make a smooth
615 transition from one time to another.
617 The return value is @code{0} on success and @code{-1} on failure. The
618 following @code{errno} error conditions are defined for this function:
622 The clock identified by @var{clock} is not supported or cannot be set
623 at all, or the simple calendar time in @code{*@var{ts}} is invalid
624 (for instance, @code{ts->tv_nsec} is negative or greater than 999,999,999).
627 This process does not have the privileges required to set the clock
628 identified by @var{clock}.
631 @strong{Portability Note}: On some systems, including systems that use
632 older versions of @theglibc{}, programs that use @code{clock_settime}
633 must be linked with the @code{-lrt} library. This has not been
634 necessary with @theglibc{} since version 2.17.
637 @cindex time, high precision
638 @cindex clock, high accuracy
639 @cindex clock, disciplining
641 For systems that remain up and running for long periods, it is not
642 enough to set the time once; one should also @dfn{discipline} the
643 clock so that it does not drift away from the true calendar time.
645 The @code{ntp_gettime} and @code{ntp_adjtime} functions provide an
646 interface to monitor and discipline the system clock. For example,
647 you can fine-tune the rate at which the clock ``ticks,'' and make
648 small adjustments to the current reported calendar time smoothly, by
649 temporarily speeding up or slowing down the clock.
651 These functions' names begin with @samp{ntp_} because they were
652 designed for use by programs implementing the Network Time Protocol to
653 synchronize a system's clock with other systems' clocks and/or with
654 external high-precision clock hardware.
656 These functions, and the constants and structures they use, are
657 declared in @file{sys/timex.h}.
659 @tindex struct ntptimeval
660 @deftp {Data Type} {struct ntptimeval}
661 This structure is used to report information about the system clock.
662 It contains the following members:
664 @item struct timeval time
665 The current calendar time, as if retrieved by @code{gettimeofday}.
666 The @code{struct timeval} data type is described in
669 @item long int maxerror
670 This is the maximum error, measured in microseconds. Unless updated
671 via @code{ntp_adjtime} periodically, this value will reach some
672 platform-specific maximum value.
674 @item long int esterror
675 This is the estimated error, measured in microseconds. This value can
676 be set by @code{ntp_adjtime} to indicate the estimated offset of the
677 system clock from the true calendar time.
681 @deftypefun int ntp_gettime (struct ntptimeval *@var{tptr})
682 @standards{GNU, sys/timex.h}
683 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
684 @c Wrapper for adjtimex.
685 The @code{ntp_gettime} function sets the structure pointed to by
686 @var{tptr} to current values. The elements of the structure afterwards
687 contain the values the timer implementation in the kernel assumes. They
688 might or might not be correct. If they are not, an @code{ntp_adjtime}
691 The return value is @code{0} on success and other values on failure. The
692 following @code{errno} error conditions are defined for this function:
696 The precision clock model is not properly set up at the moment, thus the
697 clock must be considered unsynchronized, and the values should be
703 @deftp {Data Type} {struct timex}
704 This structure is used to control and monitor the system clock. It
705 contains the following members:
707 @item unsigned int modes
708 This variable controls whether and which values are set. Several
709 symbolic constants have to be combined with @emph{binary or} to specify
710 the effective mode. These constants start with @code{MOD_}.
712 @item long int offset
713 This value indicates the current offset of the system clock from the true
714 calendar time. The value is given in microseconds. If bit
715 @code{MOD_OFFSET} is set in @code{modes}, the offset (and possibly other
716 dependent values) can be set. The offset's absolute value must not
717 exceed @code{MAXPHASE}.
720 @item long int frequency
721 This value indicates the difference in frequency between the true
722 calendar time and the system clock. The value is expressed as scaled
723 PPM (parts per million, 0.0001%). The scaling is @code{1 <<
724 SHIFT_USEC}. The value can be set with bit @code{MOD_FREQUENCY}, but
725 the absolute value must not exceed @code{MAXFREQ}.
727 @item long int maxerror
728 This is the maximum error, measured in microseconds. A new value can be
729 set using bit @code{MOD_MAXERROR}. Unless updated via
730 @code{ntp_adjtime} periodically, this value will increase steadily
731 and reach some platform-specific maximum value.
733 @item long int esterror
734 This is the estimated error, measured in microseconds. This value can
735 be set using bit @code{MOD_ESTERROR}.
738 This variable reflects the various states of the clock machinery. There
739 are symbolic constants for the significant bits, starting with
740 @code{STA_}. Some of these flags can be updated using the
741 @code{MOD_STATUS} bit.
743 @item long int constant
744 This value represents the bandwidth or stiffness of the PLL (phase
745 locked loop) implemented in the kernel. The value can be changed using
746 bit @code{MOD_TIMECONST}.
748 @item long int precision
749 This value represents the accuracy or the maximum error when reading the
750 system clock. The value is expressed in microseconds.
752 @item long int tolerance
753 This value represents the maximum frequency error of the system clock in
754 scaled PPM. This value is used to increase the @code{maxerror} every
757 @item struct timeval time
758 The current calendar time.
761 The elapsed time between clock ticks in microseconds. A clock tick is a
762 periodic timer interrupt on which the system clock is based.
764 @item long int ppsfreq
765 This is the first of a few optional variables that are present only if
766 the system clock can use a PPS (pulse per second) signal to discipline
767 the system clock. The value is expressed in scaled PPM and it denotes
768 the difference in frequency between the system clock and the PPS signal.
770 @item long int jitter
771 This value expresses a median filtered average of the PPS signal's
772 dispersion in microseconds.
775 This value is a binary exponent for the duration of the PPS calibration
776 interval, ranging from @code{PPS_SHIFT} to @code{PPS_SHIFTMAX}.
778 @item long int stabil
779 This value represents the median filtered dispersion of the PPS
780 frequency in scaled PPM.
782 @item long int jitcnt
783 This counter represents the number of pulses where the jitter exceeded
784 the allowed maximum @code{MAXTIME}.
786 @item long int calcnt
787 This counter reflects the number of successful calibration intervals.
789 @item long int errcnt
790 This counter represents the number of calibration errors (caused by
791 large offsets or jitter).
793 @item long int stbcnt
794 This counter denotes the number of calibrations where the stability
795 exceeded the threshold.
799 @deftypefun int ntp_adjtime (struct timex *@var{tptr})
800 @standards{GNU, sys/timex.h}
801 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
802 @c Alias to adjtimex syscall.
803 The @code{ntp_adjtime} function sets the structure specified by
804 @var{tptr} to current values.
806 In addition, @code{ntp_adjtime} updates some settings to match what
807 you pass to it in @code{*@var{tptr}}. Use the @code{modes} element of
808 @code{*@var{tptr}} to select what settings to update. You can set
809 @code{offset}, @code{freq}, @code{maxerror}, @code{esterror},
810 @code{status}, @code{constant}, and @code{tick}.
812 @code{modes} = zero means set nothing.
814 Only the superuser can update settings.
816 @c On Linux, ntp_adjtime() also does the adjtime() function if you set
817 @c modes = ADJ_OFFSET_SINGLESHOT (in fact, that is how GNU libc implements
818 @c adjtime()). But this should be considered an internal function because
819 @c it's so inconsistent with the rest of what ntp_adjtime() does and is
820 @c forced in an ugly way into the struct timex. So we don't document it
821 @c and instead document adjtime() as the way to achieve the function.
823 The return value is @code{0} on success and other values on failure. The
824 following @code{errno} error conditions are defined for this function:
828 The high accuracy clock model is not properly set up at the moment, thus the
829 clock must be considered unsynchronized, and the values should be
830 treated with care. Another reason could be that the specified new values
834 The process specified a settings update, but is not superuser.
838 For more details see RFC1305 (Network Time Protocol, Version 3) and
841 @strong{Portability note:} Early versions of @theglibc{} did not
842 have this function, but did have the synonymous @code{adjtimex}.
846 @c On Linux, GNU libc implements adjtime() as a call to adjtimex().
847 @deftypefun int adjtime (const struct timeval *@var{delta}, struct timeval *@var{olddelta})
848 @standards{BSD, sys/time.h}
849 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
850 @c On hurd and mach, call host_adjust_time with a privileged port. On
851 @c Linux, it's implemented in terms of adjtimex. On other unixen, it's
853 This simpler version of @code{ntp_adjtime} speeds up or slows down the
854 system clock for a short time, in order to correct it by a small
855 amount. This avoids a discontinuous change in the calendar time
856 reported by the @code{CLOCK_REALTIME} clock, at the price of having to
857 wait longer for the time to become correct.
859 The @var{delta} argument specifies a relative adjustment to be made to
860 the clock time. If negative, the system clock is slowed down for a
861 while until it has lost this much elapsed time. If positive, the system
862 clock is speeded up for a while.
864 If the @var{olddelta} argument is not a null pointer, the @code{adjtime}
865 function returns information about any previous time adjustment that
866 has not yet completed.
868 The return value is @code{0} on success and @code{-1} on failure. The
869 following @code{errno} error condition is defined for this function:
873 This process does not have the privileges required to adjust the
874 @code{CLOCK_REALTIME} clock.
878 For compatibility, @theglibc{} also provides several older functions
879 for controlling the system time. New programs should prefer to use
882 @deftypefun int stime (const time_t *@var{newtime})
883 @standards{SVID, time.h}
884 @standards{XPG, time.h}
885 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
886 Change the @code{CLOCK_REALTIME} calendar time to be the simple
887 calendar time in @code{*@var{newtime}}. Calling this function is
888 exactly the same as calling @w{@samp{clock_settime (CLOCK_REALTIME)}},
889 except that the new time can only be set to a precision of one second.
891 This function is no longer available on @gnusystems{}, but it may be
892 the @emph{only} way to set the time on very old Unix systems, so we
893 continue to document it. If it is available, it is declared in
896 The return value is @code{0} on success and @code{-1} on failure. The
897 following @code{errno} error condition is defined for this function:
901 This process does not have the privileges required to adjust the
902 @code{CLOCK_REALTIME} clock.
906 @deftypefun int adjtimex (struct timex *@var{timex})
907 @standards{GNU, sys/timex.h}
908 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
909 @code{adjtimex} is an older name for @code{ntp_adjtime}.
910 This function is only available on @gnulinuxsystems{}.
911 It is declared in @file{sys/timex.h}.
914 @deftypefun int settimeofday (const struct timeval *@var{tp}, const void *@var{tzp})
915 @standards{BSD, sys/time.h}
916 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
917 Change the @code{CLOCK_REALTIME} calendar time to be the simple
918 calendar time in @code{*@var{newtime}}. This function is declared in
921 When @var{tzp} is a null pointer, calling this function is exactly the
922 same as calling @w{@samp{clock_settime (CLOCK_REALTIME)}}, except that
923 the new time can only be set to a precision of one microsecond.
925 When @var{tzp} is not a null pointer, the data it points to @emph{may}
926 be used to set a system-wide idea of the current timezone. This
927 feature is obsolete and not supported on @gnusystems{}. Instead, use
928 the facilities described in @ref{Time Zone Functions} and in
929 @ref{Broken-down Time} for working with time zones.
931 The return value is @code{0} on success and @code{-1} on failure. The
932 following @code{errno} error conditions are defined for this function:
936 This process does not have the privileges required to set the
937 @code{CLOCK_REALTIME} clock.
940 Neither @var{tp} nor @var{tzp} is a null pointer. (For historical
941 reasons, it is not possible to set the current time and the current
942 time zone in the same call.)
945 The operating system does not support setting time zone information, and
946 @var{tzp} is not a null pointer.
950 @node Broken-down Time
951 @subsection Broken-down Time
952 @cindex broken-down time
953 @cindex calendar time and broken-down time
955 Simple calendar times represent absolute times as elapsed times since
956 an epoch. This is convenient for computation, but has no relation to
957 the way people normally think of calendar time. By contrast,
958 @dfn{broken-down time} is a binary representation of calendar time
959 separated into year, month, day, and so on. Broken-down time values
960 are not useful for calculations, but they are useful for printing
961 human readable time information.
963 A broken-down time value is always relative to a choice of time
964 zone, and it also indicates which time zone that is.
966 The symbols in this section are declared in the header file @file{time.h}.
968 @deftp {Data Type} {struct tm}
969 @standards{ISO, time.h}
970 This is the data type used to represent a broken-down time. The structure
971 contains at least the following members, which can appear in any order.
975 This is the number of full seconds since the top of the minute (normally
976 in the range @code{0} through @code{59}, but the actual upper limit is
977 @code{60}, to allow for leap seconds if leap second support is
982 This is the number of full minutes since the top of the hour (in the
983 range @code{0} through @code{59}).
986 This is the number of full hours past midnight (in the range @code{0} through
990 This is the ordinal day of the month (in the range @code{1} through @code{31}).
991 Watch out for this one! As the only ordinal number in the structure, it is
992 inconsistent with the rest of the structure.
995 This is the number of full calendar months since the beginning of the
996 year (in the range @code{0} through @code{11}). Watch out for this one!
997 People usually use ordinal numbers for month-of-year (where January = 1).
1000 This is the number of full calendar years since 1900.
1003 This is the number of full days since Sunday (in the range @code{0} through
1007 This is the number of full days since the beginning of the year (in the
1008 range @code{0} through @code{365}).
1011 @cindex Daylight Saving Time
1013 This is a flag that indicates whether Daylight Saving Time is (or was, or
1014 will be) in effect at the time described. The value is positive if
1015 Daylight Saving Time is in effect, zero if it is not, and negative if the
1016 information is not available.
1018 @item long int tm_gmtoff
1019 This field describes the time zone that was used to compute this
1020 broken-down time value, including any adjustment for daylight saving; it
1021 is the number of seconds that you must add to UTC to get local time.
1022 You can also think of this as the number of seconds east of UTC. For
1023 example, for U.S. Eastern Standard Time, the value is @code{-5*60*60}.
1024 The @code{tm_gmtoff} field is derived from BSD and is a GNU library
1025 extension; it is not visible in a strict @w{ISO C} environment.
1027 @item const char *tm_zone
1028 This field is the name for the time zone that was used to compute this
1029 broken-down time value. Like @code{tm_gmtoff}, this field is a BSD and
1030 GNU extension, and is not visible in a strict @w{ISO C} environment.
1035 @deftypefun {struct tm *} localtime (const time_t *@var{time})
1036 @standards{ISO, time.h}
1037 @safety{@prelim{}@mtunsafe{@mtasurace{:tmbuf} @mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1038 @c Calls tz_convert with a static buffer.
1039 @c localtime @mtasurace:tmbuf @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1040 @c tz_convert dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1041 The @code{localtime} function converts the simple time pointed to by
1042 @var{time} to broken-down time representation, expressed relative to the
1043 user's specified time zone.
1045 The return value is a pointer to a static broken-down time structure, which
1046 might be overwritten by subsequent calls to @code{ctime}, @code{gmtime},
1047 or @code{localtime}. (But no other library function overwrites the contents
1050 The return value is the null pointer if @var{time} cannot be represented
1051 as a broken-down time; typically this is because the year cannot fit into
1054 Calling @code{localtime} also sets the current time zone as if
1055 @code{tzset} were called. @xref{Time Zone Functions}.
1058 Using the @code{localtime} function is a big problem in multi-threaded
1059 programs. The result is returned in a static buffer and this is used in
1060 all threads. POSIX.1c introduced a variant of this function.
1062 @deftypefun {struct tm *} localtime_r (const time_t *@var{time}, struct tm *@var{resultp})
1063 @standards{POSIX.1c, time.h}
1064 @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1065 @c localtime_r @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1066 @c tz_convert(use_localtime) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1067 @c libc_lock_lock dup @asulock @aculock
1068 @c tzset_internal @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1069 @c always called with tzset_lock held
1070 @c sets static is_initialized before initialization;
1071 @c reads and sets old_tz; sets tz_rules.
1072 @c some of the issues only apply on the first call.
1073 @c subsequent calls only trigger these when called by localtime;
1074 @c otherwise, they're ok.
1075 @c getenv dup @mtsenv
1078 @c tzfile_read @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1081 @c getenv dup @mtsenv
1082 @c asprintf dup @mtslocale @ascuheap @acsmem
1084 @c fopen dup @ascuheap @asulock @acsmem @acsfd @aculock
1087 @c fclose dup @ascuheap @asulock @aculock @acsmem @acsfd
1088 @c free dup @ascuheap @acsmem
1089 @c fsetlocking dup ok [no @mtasurace:stream @asulock, exclusive]
1090 @c fread_unlocked dup ok [no @mtasurace:stream @asucorrupt @acucorrupt]
1094 @c fseek dup ok [no @mtasurace:stream @asucorrupt @acucorrupt]
1095 @c ftello dup ok [no @mtasurace:stream @asucorrupt @acucorrupt]
1096 @c malloc dup @ascuheap @acsmem
1099 @c getc_unlocked ok [no @mtasurace:stream @asucorrupt @acucorrupt]
1100 @c tzstring dup @ascuheap @acsmem
1101 @c compute_tzname_max dup ok [guarded by tzset_lock]
1103 @c update_vars ok [guarded by tzset_lock]
1104 @c sets daylight, timezone, tzname and tzname_cur_max;
1105 @c called only with tzset_lock held, unless tzset_parse_tz
1106 @c (internal, but not static) gets called by users; given the its
1107 @c double-underscore-prefixed name, this interface violation could
1108 @c be regarded as undefined behavior.
1110 @c tzset_parse_tz @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1111 @c sscanf dup @mtslocale @ascuheap @acsmem
1112 @c isalnum dup @mtsenv
1113 @c tzstring @ascuheap @acsmem
1114 @c reads and changes tzstring_list without synchronization, but
1115 @c only called with tzset_lock held (save for interface violations)
1117 @c malloc dup @ascuheap @acsmem
1119 @c isdigit dup @mtslocale
1120 @c compute_offset ok
1121 @c tzfile_default @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1122 @c sets tzname, timezone, types, zone_names, rule_*off, etc; no guards
1124 @c tzfile_read dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1126 @c compute_tzname_max ok [if guarded by tzset_lock]
1127 @c iterates over zone_names; no guards
1128 @c free dup @ascuheap @acsmem
1129 @c strtoul dup @mtslocale
1130 @c update_vars dup ok
1131 @c tzfile_compute(use_localtime) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1132 @c sets tzname; no guards. with !use_localtime, as in gmtime, it's ok
1133 @c tzstring dup @acsuheap @acsmem
1134 @c tzset_parse_tz dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1136 @c tz_compute dup ok
1141 @c compute_change ok
1143 @c libc_lock_unlock dup @aculock
1145 The @code{localtime_r} function works just like the @code{localtime}
1146 function. It takes a pointer to a variable containing a simple time
1147 and converts it to the broken-down time format.
1149 But the result is not placed in a static buffer. Instead it is placed
1150 in the object of type @code{struct tm} to which the parameter
1151 @var{resultp} points.
1153 If the conversion is successful the function returns a pointer to the
1154 object the result was written into, i.e., it returns @var{resultp}.
1158 @deftypefun {struct tm *} gmtime (const time_t *@var{time})
1159 @standards{ISO, time.h}
1160 @safety{@prelim{}@mtunsafe{@mtasurace{:tmbuf} @mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1161 @c gmtime @mtasurace:tmbuf @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1162 @c tz_convert dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1163 This function is similar to @code{localtime}, except that the broken-down
1164 time is expressed as Coordinated Universal Time (UTC) (formerly called
1165 Greenwich Mean Time (GMT)) rather than relative to a local time zone.
1169 As for the @code{localtime} function we have the problem that the result
1170 is placed in a static variable. POSIX.1c also provides a replacement for
1173 @deftypefun {struct tm *} gmtime_r (const time_t *@var{time}, struct tm *@var{resultp})
1174 @standards{POSIX.1c, time.h}
1175 @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1176 @c You'd think tz_convert could avoid some safety issues with
1177 @c !use_localtime, but no such luck: tzset_internal will always bring
1178 @c about all possible AS and AC problems when it's first called.
1179 @c Calling any of localtime,gmtime_r once would run the initialization
1180 @c and avoid the heap, mem and fd issues in gmtime* in subsequent calls,
1181 @c but the unsafe locking would remain.
1182 @c gmtime_r @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1183 @c tz_convert(gmtime_r) dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1184 This function is similar to @code{localtime_r}, except that it converts
1185 just like @code{gmtime} the given time as Coordinated Universal Time.
1187 If the conversion is successful the function returns a pointer to the
1188 object the result was written into, i.e., it returns @var{resultp}.
1192 @deftypefun time_t mktime (struct tm *@var{brokentime})
1193 @standards{ISO, time.h}
1194 @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1195 @c mktime @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1196 @c passes a static localtime_offset to mktime_internal; it is read
1197 @c once, used as an initial guess, and updated at the end, but not
1198 @c used except as a guess for subsequent calls, so it should be safe.
1199 @c Even though a compiler might delay the load and perform it multiple
1200 @c times (bug 16346), there are at least two unconditional uses of the
1201 @c auto variable in which the first load is stored, separated by a
1202 @c call to an external function, and a conditional change of the
1203 @c variable before the external call, so refraining from allocating a
1204 @c local variable at the first load would be a very bad optimization.
1205 @c tzset dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1206 @c mktime_internal(localtime_r) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1208 @c ranged_convert(localtime_r) @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1209 @c *convert = localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1210 @c time_t_avg dup ok
1211 @c guess_time_tm dup ok
1212 @c ydhms_diff dup ok
1216 @c time_t_int_add_ok ok
1217 The @code{mktime} function converts a broken-down time structure to a
1218 simple time representation. It also normalizes the contents of the
1219 broken-down time structure, and fills in some components based on the
1220 values of the others.
1222 The @code{mktime} function ignores the specified contents of the
1223 @code{tm_wday}, @code{tm_yday}, @code{tm_gmtoff}, and @code{tm_zone}
1224 members of the broken-down time
1225 structure. It uses the values of the other components to determine the
1226 calendar time; it's permissible for these components to have
1227 unnormalized values outside their normal ranges. The last thing that
1228 @code{mktime} does is adjust the components of the @var{brokentime}
1229 structure, including the members that were initially ignored.
1231 If the specified broken-down time cannot be represented as a simple time,
1232 @code{mktime} returns a value of @code{(time_t)(-1)} and does not modify
1233 the contents of @var{brokentime}.
1235 Calling @code{mktime} also sets the current time zone as if
1236 @code{tzset} were called; @code{mktime} uses this information instead
1237 of @var{brokentime}'s initial @code{tm_gmtoff} and @code{tm_zone}
1238 members. @xref{Time Zone Functions}.
1241 @deftypefun time_t timelocal (struct tm *@var{brokentime})
1242 @standards{???, time.h}
1243 @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1246 @code{timelocal} is functionally identical to @code{mktime}, but more
1247 mnemonically named. Note that it is the inverse of the @code{localtime}
1250 @strong{Portability note:} @code{mktime} is essentially universally
1251 available. @code{timelocal} is rather rare.
1255 @deftypefun time_t timegm (struct tm *@var{brokentime})
1256 @standards{???, time.h}
1257 @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1258 @c timegm @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1259 @c gmtime_offset triggers the same caveats as localtime_offset in mktime.
1260 @c although gmtime_r, as called by mktime, might save some issues,
1261 @c tzset calls tzset_internal with always, which forces
1262 @c reinitialization, so all issues may arise.
1263 @c tzset dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1264 @c mktime_internal(gmtime_r) @asulock @aculock
1265 @c ..gmtime_r @asulock @aculock
1267 @c tz_convert(!use_localtime) @asulock @aculock
1268 @c ... dup @asulock @aculock
1269 @c tzfile_compute(!use_localtime) ok
1271 @code{timegm} is functionally identical to @code{mktime} except it
1272 always takes the input values to be Coordinated Universal Time (UTC)
1273 regardless of any local time zone setting.
1275 Note that @code{timegm} is the inverse of @code{gmtime}.
1277 @strong{Portability note:} @code{mktime} is essentially universally
1278 available. @code{timegm} is rather rare. For the most portable
1279 conversion from a UTC broken-down time to a simple time, set
1280 the @code{TZ} environment variable to UTC, call @code{mktime}, then set
1287 @node Formatting Calendar Time
1288 @subsection Formatting Calendar Time
1290 The functions described in this section format calendar time values as
1291 strings. These functions are declared in the header file @file{time.h}.
1294 @deftypefun {char *} asctime (const struct tm *@var{brokentime})
1295 @standards{ISO, time.h}
1296 @safety{@prelim{}@mtunsafe{@mtasurace{:asctime} @mtslocale{}}@asunsafe{}@acsafe{}}
1297 @c asctime @mtasurace:asctime @mtslocale
1298 @c Uses a static buffer.
1299 @c asctime_internal @mtslocale
1300 @c snprintf dup @mtslocale [no @acsuheap @acsmem]
1301 @c ab_day_name @mtslocale
1302 @c ab_month_name @mtslocale
1303 The @code{asctime} function converts the broken-down time value that
1304 @var{brokentime} points to into a string in a standard format:
1307 "Tue May 21 13:46:22 1991\n"
1310 The abbreviations for the days of week are: @samp{Sun}, @samp{Mon},
1311 @samp{Tue}, @samp{Wed}, @samp{Thu}, @samp{Fri}, and @samp{Sat}.
1313 The abbreviations for the months are: @samp{Jan}, @samp{Feb},
1314 @samp{Mar}, @samp{Apr}, @samp{May}, @samp{Jun}, @samp{Jul}, @samp{Aug},
1315 @samp{Sep}, @samp{Oct}, @samp{Nov}, and @samp{Dec}.
1317 The return value points to a statically allocated string, which might be
1318 overwritten by subsequent calls to @code{asctime} or @code{ctime}.
1319 (But no other library function overwrites the contents of this
1323 @deftypefun {char *} asctime_r (const struct tm *@var{brokentime}, char *@var{buffer})
1324 @standards{POSIX.1c, time.h}
1325 @safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
1326 @c asctime_r @mtslocale
1327 @c asctime_internal dup @mtslocale
1328 This function is similar to @code{asctime} but instead of placing the
1329 result in a static buffer it writes the string in the buffer pointed to
1330 by the parameter @var{buffer}. This buffer should have room
1331 for at least 26 bytes, including the terminating null.
1333 If no error occurred the function returns a pointer to the string the
1334 result was written into, i.e., it returns @var{buffer}. Otherwise
1335 it returns @code{NULL}.
1339 @deftypefun {char *} ctime (const time_t *@var{time})
1340 @standards{ISO, time.h}
1341 @safety{@prelim{}@mtunsafe{@mtasurace{:tmbuf} @mtasurace{:asctime} @mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1342 @c ctime @mtasurace:tmbuf @mtasurace:asctime @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1343 @c localtime dup @mtasurace:tmbuf @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1344 @c asctime dup @mtasurace:asctime @mtslocale
1345 The @code{ctime} function is similar to @code{asctime}, except that you
1346 specify the calendar time argument as a @code{time_t} simple time value
1347 rather than in broken-down local time format. It is equivalent to
1350 asctime (localtime (@var{time}))
1353 Calling @code{ctime} also sets the current time zone as if
1354 @code{tzset} were called. @xref{Time Zone Functions}.
1357 @deftypefun {char *} ctime_r (const time_t *@var{time}, char *@var{buffer})
1358 @standards{POSIX.1c, time.h}
1359 @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1360 @c ctime_r @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1361 @c localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1362 @c asctime_r dup @mtslocale
1363 This function is similar to @code{ctime}, but places the result in the
1364 string pointed to by @var{buffer}. It is equivalent to (written using
1365 gcc extensions, @pxref{Statement Exprs,,,gcc,Porting and Using gcc}):
1368 (@{ struct tm tm; asctime_r (localtime_r (time, &tm), buf); @})
1371 If no error occurred the function returns a pointer to the string the
1372 result was written into, i.e., it returns @var{buffer}. Otherwise
1373 it returns @code{NULL}.
1377 @deftypefun size_t strftime (char *@var{s}, size_t @var{size}, const char *@var{template}, const struct tm *@var{brokentime})
1378 @standards{ISO, time.h}
1379 @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1380 @c strftime @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1381 @c strftime_l @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1382 @c strftime_internal @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1384 @c memset_zero dup ok
1385 @c memset_space dup ok
1387 @c mbrlen @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd [no @mtasurace:mbstate/!ps]
1391 @c memcpy_lowcase ok
1394 @c memcpy_uppcase ok
1402 @c strftime_internal dup @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1404 @c nl_get_era_entry @ascuheap @asulock @acsmem @aculock
1405 @c nl_init_era_entries @ascuheap @asulock @acsmem @aculock
1406 @c libc_rwlock_wrlock dup @asulock @aculock
1407 @c malloc dup @ascuheap @acsmem
1409 @c free dup @ascuheap @acsmem
1410 @c realloc dup @ascuheap @acsmem
1414 @c libc_rwlock_unlock dup @asulock @aculock
1417 @c DO_NUMBER_SPACEPAD ok
1418 @c nl_get_alt_digit @ascuheap @asulock @acsmem @aculock
1419 @c libc_rwlock_wrlock dup @asulock @aculock
1420 @c nl_init_alt_digit @ascuheap @acsmem
1421 @c malloc dup @ascuheap @acsmem
1424 @c libc_rwlock_unlock dup @aculock
1429 @c mktime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1432 @c tzset dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1433 @c localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1434 @c gmtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1436 This function is similar to the @code{sprintf} function (@pxref{Formatted
1437 Input}), but the conversion specifications that can appear in the format
1438 template @var{template} are specialized for printing components of the date
1439 and time @var{brokentime} according to the locale currently specified for
1440 time conversion (@pxref{Locales}) and the current time zone
1441 (@pxref{Time Zone Functions}).
1443 Ordinary characters appearing in the @var{template} are copied to the
1444 output string @var{s}; this can include multibyte character sequences.
1445 Conversion specifiers are introduced by a @samp{%} character, followed
1446 by an optional flag which can be one of the following. These flags
1447 are all GNU extensions. The first three affect only the output of
1452 The number is padded with spaces.
1455 The number is not padded at all.
1458 The number is padded with zeros even if the format specifies padding
1462 The output uses uppercase characters, but only if this is possible
1463 (@pxref{Case Conversion}).
1466 The default action is to pad the number with zeros to keep it a constant
1467 width. Numbers that do not have a range indicated below are never
1468 padded, since there is no natural width for them.
1470 Following the flag an optional specification of the width is possible.
1471 This is specified in decimal notation. If the natural size of the
1472 output of the field has less than the specified number of characters,
1473 the result is written right adjusted and space padded to the given
1476 An optional modifier can follow the optional flag and width
1477 specification. The modifiers, which were first standardized by
1478 POSIX.2-1992 and by @w{ISO C99}, are:
1482 Use the locale's alternative representation for date and time. This
1483 modifier applies to the @code{%c}, @code{%C}, @code{%x}, @code{%X},
1484 @code{%y} and @code{%Y} format specifiers. In a Japanese locale, for
1485 example, @code{%Ex} might yield a date format based on the Japanese
1489 With all format specifiers that produce numbers: use the locale's
1490 alternative numeric symbols.
1492 With @code{%B}, @code{%b}, and @code{%h}: use the grammatical form for
1493 month names that is appropriate when the month is named by itself,
1494 rather than the form that is appropriate when the month is used as
1495 part of a complete date. The @code{%OB} and @code{%Ob} formats are a
1496 C2X feature, specified in C2X to use the locale's `alternative' month
1497 name; @theglibc{} extends this specification to say that the form used
1498 in a complete date is the default and the form naming the month by
1499 itself is the alternative.
1502 If the format supports the modifier but no alternative representation
1503 is available, it is ignored.
1505 The conversion specifier ends with a format specifier taken from the
1506 following list. The whole @samp{%} sequence is replaced in the output
1511 The abbreviated weekday name according to the current locale.
1514 The full weekday name according to the current locale.
1517 The abbreviated month name according to the current locale, in the
1518 grammatical form used when the month is part of a complete date.
1519 As a C2X feature (with a more detailed specification in @theglibc{}),
1520 the @code{O} modifier can be used (@code{%Ob}) to get the grammatical
1521 form used when the month is named by itself.
1524 The full month name according to the current locale, in the
1525 grammatical form used when the month is part of a complete date.
1526 As a C2X feature (with a more detailed specification in @theglibc{}),
1527 the @code{O} modifier can be used (@code{%OB}) to get the grammatical
1528 form used when the month is named by itself.
1530 Note that not all languages need two different forms of the month
1531 names, so the text produced by @code{%B} and @code{%OB}, and by
1532 @code{%b} and @code{%Ob}, may or may not be the same, depending on
1536 The preferred calendar time representation for the current locale.
1539 The century of the year. This is equivalent to the greatest integer not
1540 greater than the year divided by 100.
1542 If the @code{E} modifier is specified (@code{%EC}), instead produces
1543 the name of the period for the year (e.g.@: an era name) in the
1544 locale's alternative calendar.
1546 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1549 The day of the month as a decimal number (range @code{01} through @code{31}).
1552 The date using the format @code{%m/%d/%y}.
1554 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1557 The day of the month like with @code{%d}, but padded with spaces (range
1558 @code{ 1} through @code{31}).
1560 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1563 The date using the format @code{%Y-%m-%d}. This is the form specified
1564 in the @w{ISO 8601} standard and is the preferred form for all uses.
1566 This format was first standardized by @w{ISO C99} and by POSIX.1-2001.
1569 The year corresponding to the ISO week number, but without the century
1570 (range @code{00} through @code{99}). This has the same format and value
1571 as @code{%y}, except that if the ISO week number (see @code{%V}) belongs
1572 to the previous or next year, that year is used instead.
1574 This format was first standardized by @w{ISO C99} and by POSIX.1-2001.
1577 The year corresponding to the ISO week number. This has the same format
1578 and value as @code{%Y}, except that if the ISO week number (see
1579 @code{%V}) belongs to the previous or next year, that year is used
1582 This format was first standardized by @w{ISO C99} and by POSIX.1-2001
1583 but was previously available as a GNU extension.
1586 The abbreviated month name according to the current locale. The action
1587 is the same as for @code{%b}.
1589 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1592 The hour as a decimal number, using a 24-hour clock (range @code{00} through
1596 The hour as a decimal number, using a 12-hour clock (range @code{01} through
1600 The day of the year as a decimal number (range @code{001} through @code{366}).
1603 The hour as a decimal number, using a 24-hour clock like @code{%H}, but
1604 padded with spaces (range @code{ 0} through @code{23}).
1606 This format is a GNU extension.
1609 The hour as a decimal number, using a 12-hour clock like @code{%I}, but
1610 padded with spaces (range @code{ 1} through @code{12}).
1612 This format is a GNU extension.
1615 The month as a decimal number (range @code{01} through @code{12}).
1618 The minute as a decimal number (range @code{00} through @code{59}).
1621 A single @samp{\n} (newline) character.
1623 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1626 Either @samp{AM} or @samp{PM}, according to the given time value; or the
1627 corresponding strings for the current locale. Noon is treated as
1628 @samp{PM} and midnight as @samp{AM}. In most locales
1629 @samp{AM}/@samp{PM} format is not supported, in such cases @code{"%p"}
1630 yields an empty string.
1633 We currently have a problem with makeinfo. Write @samp{AM} and @samp{am}
1634 both results in `am'. I.e., the difference in case is not visible anymore.
1637 Either @samp{am} or @samp{pm}, according to the given time value; or the
1638 corresponding strings for the current locale, printed in lowercase
1639 characters. Noon is treated as @samp{pm} and midnight as @samp{am}. In
1640 most locales @samp{AM}/@samp{PM} format is not supported, in such cases
1641 @code{"%P"} yields an empty string.
1643 This format is a GNU extension.
1646 The complete calendar time using the AM/PM format of the current locale.
1648 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1649 In the POSIX locale, this format is equivalent to @code{%I:%M:%S %p}.
1652 The hour and minute in decimal numbers using the format @code{%H:%M}.
1654 This format was first standardized by @w{ISO C99} and by POSIX.1-2001
1655 but was previously available as a GNU extension.
1658 The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
1659 Leap seconds are not counted unless leap second support is available.
1661 This format is a GNU extension.
1664 The seconds as a decimal number (range @code{00} through @code{60}).
1667 A single @samp{\t} (tabulator) character.
1669 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1672 The time of day using decimal numbers using the format @code{%H:%M:%S}.
1674 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1677 The day of the week as a decimal number (range @code{1} through
1678 @code{7}), Monday being @code{1}.
1680 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1683 The week number of the current year as a decimal number (range @code{00}
1684 through @code{53}), starting with the first Sunday as the first day of
1685 the first week. Days preceding the first Sunday in the year are
1686 considered to be in week @code{00}.
1689 The @w{ISO 8601:1988} week number as a decimal number (range @code{01}
1690 through @code{53}). ISO weeks start with Monday and end with Sunday.
1691 Week @code{01} of a year is the first week which has the majority of its
1692 days in that year; this is equivalent to the week containing the year's
1693 first Thursday, and it is also equivalent to the week containing January
1694 4. Week @code{01} of a year can contain days from the previous year.
1695 The week before week @code{01} of a year is the last week (@code{52} or
1696 @code{53}) of the previous year even if it contains days from the new
1699 This format was first standardized by POSIX.2-1992 and by @w{ISO C99}.
1702 The day of the week as a decimal number (range @code{0} through
1703 @code{6}), Sunday being @code{0}.
1706 The week number of the current year as a decimal number (range @code{00}
1707 through @code{53}), starting with the first Monday as the first day of
1708 the first week. All days preceding the first Monday in the year are
1709 considered to be in week @code{00}.
1712 The preferred date representation for the current locale.
1715 The preferred time of day representation for the current locale.
1718 The year without a century as a decimal number (range @code{00} through
1719 @code{99}). This is equivalent to the year modulo 100.
1721 If the @code{E} modifier is specified (@code{%Ey}), instead produces
1722 the year number according to a locale-specific alternative calendar.
1723 Unlike @code{%y}, the number is @emph{not} reduced modulo 100.
1724 However, by default it is zero-padded to a minimum of two digits (this
1725 can be overridden by an explicit field width or by the @code{_} and
1729 The year as a decimal number, using the Gregorian calendar. Years
1730 before the year @code{1} are numbered @code{0}, @code{-1}, and so on.
1732 If the @code{E} modifier is specified (@code{%EY}), instead produces a
1733 complete representation of the year according to the locale's
1734 alternative calendar. Generally this will be some combination of the
1735 information produced by @code{%EC} and @code{%Ey}. As a GNU
1736 extension, the formatting flags @code{_} or @code{-} may be used with
1737 this conversion specifier; they affect how the year number is printed.
1740 @w{RFC 822}/@w{ISO 8601:1988} style numeric time zone (e.g.,
1741 @code{-0600} or @code{+0100}), or nothing if no time zone is
1744 This format was first standardized by @w{ISO C99} and by POSIX.1-2001
1745 but was previously available as a GNU extension.
1747 In the POSIX locale, a full @w{RFC 822} timestamp is generated by the format
1748 @w{@samp{"%a, %d %b %Y %H:%M:%S %z"}} (or the equivalent
1749 @w{@samp{"%a, %d %b %Y %T %z"}}).
1752 The time zone abbreviation (empty if the time zone can't be determined).
1755 A literal @samp{%} character.
1758 The @var{size} parameter can be used to specify the maximum number of
1759 characters to be stored in the array @var{s}, including the terminating
1760 null character. If the formatted time requires more than @var{size}
1761 characters, @code{strftime} returns zero and the contents of the array
1762 @var{s} are undefined. Otherwise the return value indicates the
1763 number of characters placed in the array @var{s}, not including the
1764 terminating null character.
1766 @emph{Warning:} This convention for the return value which is prescribed
1767 in @w{ISO C} can lead to problems in some situations. For certain
1768 format strings and certain locales the output really can be the empty
1769 string and this cannot be discovered by testing the return value only.
1770 E.g., in most locales the AM/PM time format is not supported (most of
1771 the world uses the 24 hour time representation). In such locales
1772 @code{"%p"} will return the empty string, i.e., the return value is
1773 zero. To detect situations like this something similar to the following
1774 code should be used:
1778 len = strftime (buf, bufsize, format, tp);
1779 if (len == 0 && buf[0] != '\0')
1781 /* Something went wrong in the strftime call. */
1786 If @var{s} is a null pointer, @code{strftime} does not actually write
1787 anything, but instead returns the number of characters it would have written.
1789 Calling @code{strftime} also sets the current time zone as if
1790 @code{tzset} were called; @code{strftime} uses this information
1791 instead of @var{brokentime}'s @code{tm_gmtoff} and @code{tm_zone}
1792 members. @xref{Time Zone Functions}.
1794 For an example of @code{strftime}, see @ref{Time Functions Example}.
1797 @deftypefun size_t wcsftime (wchar_t *@var{s}, size_t @var{size}, const wchar_t *@var{template}, const struct tm *@var{brokentime})
1798 @standards{ISO/Amend1, time.h}
1799 @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{} @asulock{} @ascudlopen{}}@acunsafe{@acucorrupt{} @aculock{} @acsmem{} @acsfd{}}}
1800 @c wcsftime @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1801 @c wcsftime_l @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1802 @c wcsftime_internal @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1804 @c memset_zero dup ok
1805 @c memset_space dup ok
1809 @c memcpy_lowcase ok
1811 @c towlower_l dup ok
1812 @c memcpy_uppcase ok
1814 @c towupper_l dup ok
1817 @c widen @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1819 @c mbsrtowcs_l @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd [no @mtasurace:mbstate/!ps]
1823 @c wcsftime_internal dup @mtsenv @mtslocale @asucorrupt @ascuheap @asulock @ascudlopen @acucorrupt @aculock @acsmem @acsfd
1825 @c nl_get_era_entry dup @ascuheap @asulock @acsmem @aculock
1827 @c DO_NUMBER_SPACEPAD ok
1828 @c nl_get_walt_digit dup @ascuheap @asulock @acsmem @aculock
1829 @c libc_rwlock_wrlock dup @asulock @aculock
1830 @c nl_init_alt_digit dup @ascuheap @acsmem
1831 @c malloc dup @ascuheap @acsmem
1834 @c libc_rwlock_unlock dup @aculock
1839 @c mktime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1842 @c tzset dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1843 @c localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1844 @c gmtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1846 The @code{wcsftime} function is equivalent to the @code{strftime}
1847 function with the difference that it operates on wide character
1848 strings. The buffer where the result is stored, pointed to by @var{s},
1849 must be an array of wide characters. The parameter @var{size} which
1850 specifies the size of the output buffer gives the number of wide
1851 characters, not the number of bytes.
1853 Also the format string @var{template} is a wide character string. Since
1854 all characters needed to specify the format string are in the basic
1855 character set it is portably possible to write format strings in the C
1856 source code using the @code{L"@dots{}"} notation. The parameter
1857 @var{brokentime} has the same meaning as in the @code{strftime} call.
1859 The @code{wcsftime} function supports the same flags, modifiers, and
1860 format specifiers as the @code{strftime} function.
1862 The return value of @code{wcsftime} is the number of wide characters
1863 stored in @code{s}. When more characters would have to be written than
1864 can be placed in the buffer @var{s} the return value is zero, with the
1865 same problems indicated in the @code{strftime} documentation.
1868 @node Parsing Date and Time
1869 @subsection Convert textual time and date information back
1871 The @w{ISO C} standard does not specify any functions which can convert
1872 the output of the @code{strftime} function back into a binary format.
1873 This led to a variety of more-or-less successful implementations with
1874 different interfaces over the years. Then the Unix standard was
1875 extended by the addition of two functions: @code{strptime} and
1876 @code{getdate}. Both have strange interfaces but at least they are
1880 * Low-Level Time String Parsing:: Interpret string according to given format.
1881 * General Time String Parsing:: User-friendly function to parse data and
1885 @node Low-Level Time String Parsing
1886 @subsubsection Interpret string according to given format
1888 The first function is rather low-level. It is nevertheless frequently
1889 used in software since it is better known. Its interface and
1890 implementation are heavily influenced by the @code{getdate} function,
1891 which is defined and implemented in terms of calls to @code{strptime}.
1893 @deftypefun {char *} strptime (const char *@var{s}, const char *@var{fmt}, struct tm *@var{tp})
1894 @standards{XPG4, time.h}
1895 @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
1896 @c strptime @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1897 @c strptime_internal @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1904 @c strncasecmp_l dup ok
1906 @c recursive @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1907 @c strptime_internal dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1910 @c localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
1911 @c nl_select_era_entry @ascuheap @asulock @acsmem @aculock
1912 @c nl_init_era_entries dup @ascuheap @asulock @acsmem @aculock
1913 @c get_alt_number dup @ascuheap @asulock @acsmem @aculock
1914 @c nl_parse_alt_digit dup @ascuheap @asulock @acsmem @aculock
1915 @c libc_rwlock_wrlock dup @asulock @aculock
1916 @c nl_init_alt_digit dup @ascuheap @acsmem
1917 @c libc_rwlock_unlock dup @aculock
1918 @c get_number dup ok
1919 @c day_of_the_week ok
1920 @c day_of_the_year ok
1921 The @code{strptime} function parses the input string @var{s} according
1922 to the format string @var{fmt} and stores its results in the
1925 The input string could be generated by a @code{strftime} call or
1926 obtained any other way. It does not need to be in a human-recognizable
1927 format; e.g. a date passed as @code{"02:1999:9"} is acceptable, even
1928 though it is ambiguous without context. As long as the format string
1929 @var{fmt} matches the input string the function will succeed.
1931 The user has to make sure, though, that the input can be parsed in a
1932 unambiguous way. The string @code{"1999112"} can be parsed using the
1933 format @code{"%Y%m%d"} as 1999-1-12, 1999-11-2, or even 19991-1-2. It
1934 is necessary to add appropriate separators to reliably get results.
1936 The format string consists of the same components as the format string
1937 of the @code{strftime} function. The only difference is that the flags
1938 @code{_}, @code{-}, @code{0}, and @code{^} are not allowed.
1939 @comment Is this really the intention? --drepper
1940 Several of the distinct formats of @code{strftime} do the same work in
1941 @code{strptime} since differences like case of the input do not matter.
1942 For reasons of symmetry all formats are supported, though.
1944 The modifiers @code{E} and @code{O} are also allowed everywhere the
1945 @code{strftime} function allows them.
1952 The weekday name according to the current locale, in abbreviated form or
1958 A month name according to the current locale. All three specifiers
1959 will recognize both abbreviated and full month names. If the
1960 locale provides two different grammatical forms of month names,
1961 all three specifiers will recognize both forms.
1963 As a GNU extension, the @code{O} modifier can be used with these
1964 specifiers; it has no effect, as both grammatical forms of month
1965 names are recognized.
1968 The date and time representation for the current locale.
1971 Like @code{%c} but the locale's alternative date and time format is used.
1974 The century of the year.
1976 It makes sense to use this format only if the format string also
1977 contains the @code{%y} format.
1980 The locale's representation of the period.
1982 Unlike @code{%C} it sometimes makes sense to use this format since some
1983 cultures represent years relative to the beginning of eras instead of
1984 using the Gregorian years.
1988 The day of the month as a decimal number (range @code{1} through @code{31}).
1989 Leading zeroes are permitted but not required.
1993 Same as @code{%d} but using the locale's alternative numeric symbols.
1995 Leading zeroes are permitted but not required.
1998 Equivalent to @code{%m/%d/%y}.
2001 Equivalent to @code{%Y-%m-%d}, which is the @w{ISO 8601} date
2004 This is a GNU extension following an @w{ISO C99} extension to
2008 The year corresponding to the ISO week number, but without the century
2009 (range @code{00} through @code{99}).
2011 @emph{Note:} Currently, this is not fully implemented. The format is
2012 recognized, input is consumed but no field in @var{tm} is set.
2014 This format is a GNU extension following a GNU extension of @code{strftime}.
2017 The year corresponding to the ISO week number.
2019 @emph{Note:} Currently, this is not fully implemented. The format is
2020 recognized, input is consumed but no field in @var{tm} is set.
2022 This format is a GNU extension following a GNU extension of @code{strftime}.
2026 The hour as a decimal number, using a 24-hour clock (range @code{00} through
2029 @code{%k} is a GNU extension following a GNU extension of @code{strftime}.
2032 Same as @code{%H} but using the locale's alternative numeric symbols.
2036 The hour as a decimal number, using a 12-hour clock (range @code{01} through
2039 @code{%l} is a GNU extension following a GNU extension of @code{strftime}.
2042 Same as @code{%I} but using the locale's alternative numeric symbols.
2045 The day of the year as a decimal number (range @code{1} through @code{366}).
2047 Leading zeroes are permitted but not required.
2050 The month as a decimal number (range @code{1} through @code{12}).
2052 Leading zeroes are permitted but not required.
2055 Same as @code{%m} but using the locale's alternative numeric symbols.
2058 The minute as a decimal number (range @code{0} through @code{59}).
2060 Leading zeroes are permitted but not required.
2063 Same as @code{%M} but using the locale's alternative numeric symbols.
2067 Matches any white space.
2071 The locale-dependent equivalent to @samp{AM} or @samp{PM}.
2073 This format is not useful unless @code{%I} or @code{%l} is also used.
2074 Another complication is that the locale might not define these values at
2075 all and therefore the conversion fails.
2077 @code{%P} is a GNU extension following a GNU extension to @code{strftime}.
2080 The complete time using the AM/PM format of the current locale.
2082 A complication is that the locale might not define this format at all
2083 and therefore the conversion fails.
2086 The hour and minute in decimal numbers using the format @code{%H:%M}.
2088 @code{%R} is a GNU extension following a GNU extension to @code{strftime}.
2091 The number of seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
2092 Leap seconds are not counted unless leap second support is available.
2094 @code{%s} is a GNU extension following a GNU extension to @code{strftime}.
2097 The seconds as a decimal number (range @code{0} through @code{60}).
2099 Leading zeroes are permitted but not required.
2101 @strong{NB:} The Unix specification says the upper bound on this value
2102 is @code{61}, a result of a decision to allow double leap seconds. You
2103 will not see the value @code{61} because no minute has more than one
2104 leap second, but the myth persists.
2107 Same as @code{%S} but using the locale's alternative numeric symbols.
2110 Equivalent to the use of @code{%H:%M:%S} in this place.
2113 The day of the week as a decimal number (range @code{1} through
2114 @code{7}), Monday being @code{1}.
2116 Leading zeroes are permitted but not required.
2118 @emph{Note:} Currently, this is not fully implemented. The format is
2119 recognized, input is consumed but no field in @var{tm} is set.
2122 The week number of the current year as a decimal number (range @code{0}
2125 Leading zeroes are permitted but not required.
2128 Same as @code{%U} but using the locale's alternative numeric symbols.
2131 The @w{ISO 8601:1988} week number as a decimal number (range @code{1}
2134 Leading zeroes are permitted but not required.
2136 @emph{Note:} Currently, this is not fully implemented. The format is
2137 recognized, input is consumed but no field in @var{tm} is set.
2140 The day of the week as a decimal number (range @code{0} through
2141 @code{6}), Sunday being @code{0}.
2143 Leading zeroes are permitted but not required.
2145 @emph{Note:} Currently, this is not fully implemented. The format is
2146 recognized, input is consumed but no field in @var{tm} is set.
2149 Same as @code{%w} but using the locale's alternative numeric symbols.
2152 The week number of the current year as a decimal number (range @code{0}
2155 Leading zeroes are permitted but not required.
2157 @emph{Note:} Currently, this is not fully implemented. The format is
2158 recognized, input is consumed but no field in @var{tm} is set.
2161 Same as @code{%W} but using the locale's alternative numeric symbols.
2164 The date using the locale's date format.
2167 Like @code{%x} but the locale's alternative data representation is used.
2170 The time using the locale's time format.
2173 Like @code{%X} but the locale's alternative time representation is used.
2176 The year without a century as a decimal number (range @code{0} through
2179 Leading zeroes are permitted but not required.
2181 Note that it is questionable to use this format without
2182 the @code{%C} format. The @code{strptime} function does regard input
2183 values in the range @math{68} to @math{99} as the years @math{1969} to
2184 @math{1999} and the values @math{0} to @math{68} as the years
2185 @math{2000} to @math{2068}. But maybe this heuristic fails for some
2188 Therefore it is best to avoid @code{%y} completely and use @code{%Y}
2192 The offset from @code{%EC} in the locale's alternative representation.
2195 The offset of the year (from @code{%C}) using the locale's alternative
2199 The year as a decimal number, using the Gregorian calendar.
2202 The full alternative year representation.
2205 The offset from GMT in @w{ISO 8601}/RFC822 format.
2210 @emph{Note:} Currently, this is not fully implemented. The format is
2211 recognized, input is consumed but no field in @var{tm} is set.
2214 A literal @samp{%} character.
2217 All other characters in the format string must have a matching character
2218 in the input string. Exceptions are white spaces in the input string
2219 which can match zero or more whitespace characters in the format string.
2221 @strong{Portability Note:} The XPG standard advises applications to use
2222 at least one whitespace character (as specified by @code{isspace}) or
2223 other non-alphanumeric characters between any two conversion
2224 specifications. @Theglibc{} does not have this limitation but
2225 other libraries might have trouble parsing formats like
2226 @code{"%d%m%Y%H%M%S"}.
2228 The @code{strptime} function processes the input string from right to
2229 left. Each of the three possible input elements (white space, literal,
2230 or format) are handled one after the other. If the input cannot be
2231 matched to the format string the function stops. The remainder of the
2232 format and input strings are not processed.
2234 The function returns a pointer to the first character it was unable to
2235 process. If the input string contains more characters than required by
2236 the format string the return value points right after the last consumed
2237 input character. If the whole input string is consumed the return value
2238 points to the @code{NULL} byte at the end of the string. If an error
2239 occurs, i.e., @code{strptime} fails to match all of the format string,
2240 the function returns @code{NULL}.
2243 The specification of the function in the XPG standard is rather vague,
2244 leaving out a few important pieces of information. Most importantly, it
2245 does not specify what happens to those elements of @var{tm} which are
2246 not directly initialized by the different formats. The
2247 implementations on different Unix systems vary here.
2249 The @glibcadj{} implementation does not touch those fields which are not
2250 directly initialized. Exceptions are the @code{tm_wday} and
2251 @code{tm_yday} elements, which are recomputed if any of the year, month,
2252 or date elements changed. This has two implications:
2256 Before calling the @code{strptime} function for a new input string, you
2257 should prepare the @var{tm} structure you pass. Normally this will mean
2258 initializing all values to zero. Alternatively, you can set all
2259 fields to values like @code{INT_MAX}, allowing you to determine which
2260 elements were set by the function call. Zero does not work here since
2261 it is a valid value for many of the fields.
2263 Careful initialization is necessary if you want to find out whether a
2264 certain field in @var{tm} was initialized by the function call.
2267 You can construct a @code{struct tm} value with several consecutive
2268 @code{strptime} calls. A useful application of this is e.g. the parsing
2269 of two separate strings, one containing date information and the other
2270 time information. By parsing one after the other without clearing the
2271 structure in-between, you can construct a complete broken-down time.
2274 The following example shows a function which parses a string which
2275 contains the date information in either US style or @w{ISO 8601} form:
2279 parse_date (const char *input, struct tm *tm)
2283 /* @r{First clear the result structure.} */
2284 memset (tm, '\0', sizeof (*tm));
2286 /* @r{Try the ISO format first.} */
2287 cp = strptime (input, "%F", tm);
2290 /* @r{Does not match. Try the US form.} */
2291 cp = strptime (input, "%D", tm);
2298 @node General Time String Parsing
2299 @subsubsection A More User-friendly Way to Parse Times and Dates
2301 The Unix standard defines another function for parsing date strings.
2302 The interface is weird, but if the function happens to suit your
2303 application it is just fine. It is problematic to use this function
2304 in multi-threaded programs or libraries, since it returns a pointer to
2305 a static variable, and uses a global variable and global state (an
2306 environment variable).
2309 @standards{Unix98, time.h}
2310 This variable of type @code{int} contains the error code of the last
2311 unsuccessful call to @code{getdate}. Defined values are:
2315 The environment variable @code{DATEMSK} is not defined or null.
2317 The template file denoted by the @code{DATEMSK} environment variable
2320 Information about the template file cannot retrieved.
2322 The template file is not a regular file.
2324 An I/O error occurred while reading the template file.
2326 Not enough memory available to execute the function.
2328 The template file contains no matching template.
2330 The input date is invalid, but would match a template otherwise. This
2331 includes dates like February 31st, and dates which cannot be represented
2332 in a @code{time_t} variable.
2336 @deftypefun {struct tm *} getdate (const char *@var{string})
2337 @standards{Unix98, time.h}
2338 @safety{@prelim{}@mtunsafe{@mtasurace{:getdate} @mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
2339 @c getdate @mtasurace:getdate @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2340 @c getdate_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2341 The interface to @code{getdate} is the simplest possible for a function
2342 to parse a string and return the value. @var{string} is the input
2343 string and the result is returned in a statically-allocated variable.
2345 The details about how the string is processed are hidden from the user.
2346 In fact, they can be outside the control of the program. Which formats
2347 are recognized is controlled by the file named by the environment
2348 variable @code{DATEMSK}. This file should contain
2349 lines of valid format strings which could be passed to @code{strptime}.
2351 The @code{getdate} function reads these format strings one after the
2352 other and tries to match the input string. The first line which
2353 completely matches the input string is used.
2355 Elements not initialized through the format string retain the values
2356 present at the time of the @code{getdate} function call.
2358 The formats recognized by @code{getdate} are the same as for
2359 @code{strptime}. See above for an explanation. There are only a few
2360 extensions to the @code{strptime} behavior:
2364 If the @code{%Z} format is given the broken-down time is based on the
2365 current time of the timezone matched, not of the current timezone of the
2366 runtime environment.
2368 @emph{Note}: This is not implemented (currently). The problem is that
2369 timezone names are not unique. If a fixed timezone is assumed for a
2370 given string (say @code{EST} meaning US East Coast time), then uses for
2371 countries other than the USA will fail. So far we have found no good
2375 If only the weekday is specified the selected day depends on the current
2376 date. If the current weekday is greater than or equal to the @code{tm_wday}
2377 value the current week's day is chosen, otherwise the day next week is chosen.
2380 A similar heuristic is used when only the month is given and not the
2381 year. If the month is greater than or equal to the current month, then
2382 the current year is used. Otherwise it wraps to next year. The first
2383 day of the month is assumed if one is not explicitly specified.
2386 The current hour, minute, and second are used if the appropriate value is
2387 not set through the format.
2390 If no date is given tomorrow's date is used if the time is
2391 smaller than the current time. Otherwise today's date is taken.
2394 It should be noted that the format in the template file need not only
2395 contain format elements. The following is a list of possible format
2396 strings (taken from the Unix standard):
2400 %A %B %d, %Y %H:%M:%S
2405 at %A the %dst of %B in %Y
2406 run job at %I %p,%B %dnd
2407 %A den %d. %B %Y %H.%M Uhr
2410 As you can see, the template list can contain very specific strings like
2411 @code{run job at %I %p,%B %dnd}. Using the above list of templates and
2412 assuming the current time is Mon Sep 22 12:19:47 EDT 1986, we can obtain the
2413 following results for the given input.
2415 @multitable {xxxxxxxxxxxx} {xxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
2416 @item Input @tab Match @tab Result
2417 @item Mon @tab %a @tab Mon Sep 22 12:19:47 EDT 1986
2418 @item Sun @tab %a @tab Sun Sep 28 12:19:47 EDT 1986
2419 @item Fri @tab %a @tab Fri Sep 26 12:19:47 EDT 1986
2420 @item September @tab %B @tab Mon Sep 1 12:19:47 EDT 1986
2421 @item January @tab %B @tab Thu Jan 1 12:19:47 EST 1987
2422 @item December @tab %B @tab Mon Dec 1 12:19:47 EST 1986
2423 @item Sep Mon @tab %b %a @tab Mon Sep 1 12:19:47 EDT 1986
2424 @item Jan Fri @tab %b %a @tab Fri Jan 2 12:19:47 EST 1987
2425 @item Dec Mon @tab %b %a @tab Mon Dec 1 12:19:47 EST 1986
2426 @item Jan Wed 1989 @tab %b %a %Y @tab Wed Jan 4 12:19:47 EST 1989
2427 @item Fri 9 @tab %a %H @tab Fri Sep 26 09:00:00 EDT 1986
2428 @item Feb 10:30 @tab %b %H:%S @tab Sun Feb 1 10:00:30 EST 1987
2429 @item 10:30 @tab %H:%M @tab Tue Sep 23 10:30:00 EDT 1986
2430 @item 13:30 @tab %H:%M @tab Mon Sep 22 13:30:00 EDT 1986
2433 The return value of the function is a pointer to a static variable of
2434 type @w{@code{struct tm}}, or a null pointer if an error occurred. The
2435 result is only valid until the next @code{getdate} call, making this
2436 function unusable in multi-threaded applications.
2438 The @code{errno} variable is @emph{not} changed. Error conditions are
2439 stored in the global variable @code{getdate_err}. See the
2440 description above for a list of the possible error values.
2442 @emph{Warning:} The @code{getdate} function should @emph{never} be
2443 used in SUID-programs. The reason is obvious: using the
2444 @code{DATEMSK} environment variable you can get the function to open
2445 any arbitrary file and chances are high that with some bogus input
2446 (such as a binary file) the program will crash.
2449 @deftypefun int getdate_r (const char *@var{string}, struct tm *@var{tp})
2450 @standards{GNU, time.h}
2451 @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
2452 @c getdate_r @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2453 @c getenv dup @mtsenv
2456 @c fopen dup @ascuheap @asulock @acsmem @acsfd @aculock
2457 @c fsetlocking dup ok [no @mtasurace:stream @asulock, exclusive]
2458 @c isspace dup @mtslocale
2460 @c malloc dup @ascuheap @acsmem
2461 @c fclose dup @ascuheap @asulock @aculock @acsmem @acsfd
2463 @c getline dup @ascuheap @acsmem [no @asucorrupt @aculock @acucorrupt, exclusive]
2464 @c strptime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2465 @c feof_unlocked dup ok
2466 @c free dup @ascuheap @acsmem
2467 @c ferror_unlocked dup dup ok
2469 @c localtime_r dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2470 @c first_wday @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2472 @c mktime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2474 @c mktime dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2475 The @code{getdate_r} function is the reentrant counterpart of
2476 @code{getdate}. It does not use the global variable @code{getdate_err}
2477 to signal an error, but instead returns an error code. The same error
2478 codes as described in the @code{getdate_err} documentation above are
2479 used, with 0 meaning success.
2481 Moreover, @code{getdate_r} stores the broken-down time in the variable
2482 of type @code{struct tm} pointed to by the second argument, rather than
2483 in a static variable.
2485 This function is not defined in the Unix standard. Nevertheless it is
2486 available on some other Unix systems as well.
2488 The warning against using @code{getdate} in SUID-programs applies to
2489 @code{getdate_r} as well.
2493 @subsection Specifying the Time Zone with @code{TZ}
2495 In POSIX systems, a user can specify the time zone by means of the
2496 @code{TZ} environment variable. For information about how to set
2497 environment variables, see @ref{Environment Variables}. The functions
2498 for accessing the time zone are declared in @file{time.h}.
2502 You should not normally need to set @code{TZ}. If the system is
2503 configured properly, the default time zone will be correct. You might
2504 set @code{TZ} if you are using a computer over a network from a
2505 different time zone, and would like times reported to you in the time
2506 zone local to you, rather than what is local to the computer.
2508 In POSIX.1 systems the value of the @code{TZ} variable can be in one of
2509 three formats. With @theglibc{}, the most common format is the
2510 last one, which can specify a selection from a large database of time
2511 zone information for many regions of the world. The first two formats
2512 are used to describe the time zone information directly, which is both
2513 more cumbersome and less precise. But the POSIX.1 standard only
2514 specifies the details of the first two formats, so it is good to be
2515 familiar with them in case you come across a POSIX.1 system that doesn't
2516 support a time zone information database.
2518 The first format is used when there is no Daylight Saving Time (or
2519 summer time) in the local time zone:
2522 @r{@var{std} @var{offset}}
2525 The @var{std} string specifies the name of the time zone. It must be
2526 three or more characters long and must not contain a leading colon,
2527 embedded digits, commas, nor plus and minus signs. There is no space
2528 character separating the time zone name from the @var{offset}, so these
2529 restrictions are necessary to parse the specification correctly.
2531 The @var{offset} specifies the time value you must add to the local time
2532 to get a Coordinated Universal Time value. It has syntax like
2533 [@code{+}|@code{-}]@var{hh}[@code{:}@var{mm}[@code{:}@var{ss}]]. This
2534 is positive if the local time zone is west of the Prime Meridian and
2535 negative if it is east. The hour must be between @code{0} and
2536 @code{24}, and the minute and seconds between @code{0} and @code{59}.
2538 For example, here is how we would specify Eastern Standard Time, but
2539 without any Daylight Saving Time alternative:
2545 The second format is used when there is Daylight Saving Time:
2548 @r{@var{std} @var{offset} @var{dst} [@var{offset}]@code{,}@var{start}[@code{/}@var{time}]@code{,}@var{end}[@code{/}@var{time}]}
2551 The initial @var{std} and @var{offset} specify the standard time zone, as
2552 described above. The @var{dst} string and @var{offset} specify the name
2553 and offset for the corresponding Daylight Saving Time zone; if the
2554 @var{offset} is omitted, it defaults to one hour ahead of standard time.
2556 The remainder of the specification describes when Daylight Saving Time is
2557 in effect. The @var{start} field is when Daylight Saving Time goes into
2558 effect and the @var{end} field is when the change is made back to standard
2559 time. The following formats are recognized for these fields:
2563 This specifies the Julian day, with @var{n} between @code{1} and @code{365}.
2564 February 29 is never counted, even in leap years.
2567 This specifies the Julian day, with @var{n} between @code{0} and @code{365}.
2568 February 29 is counted in leap years.
2570 @item M@var{m}.@var{w}.@var{d}
2571 This specifies day @var{d} of week @var{w} of month @var{m}. The day
2572 @var{d} must be between @code{0} (Sunday) and @code{6}. The week
2573 @var{w} must be between @code{1} and @code{5}; week @code{1} is the
2574 first week in which day @var{d} occurs, and week @code{5} specifies the
2575 @emph{last} @var{d} day in the month. The month @var{m} should be
2576 between @code{1} and @code{12}.
2579 The @var{time} fields specify when, in the local time currently in
2580 effect, the change to the other time occurs. If omitted, the default is
2581 @code{02:00:00}. The hours part of the time fields can range from
2582 @minus{}167 through 167; this is an extension to POSIX.1, which allows
2583 only the range 0 through 24.
2585 Here are some example @code{TZ} values, including the appropriate
2586 Daylight Saving Time and its dates of applicability. In North
2587 American Eastern Standard Time (EST) and Eastern Daylight Time (EDT),
2588 the normal offset from UTC is 5 hours; since this is
2589 west of the prime meridian, the sign is positive. Summer time begins on
2590 March's second Sunday at 2:00am, and ends on November's first Sunday
2594 EST+5EDT,M3.2.0/2,M11.1.0/2
2597 Israel Standard Time (IST) and Israel Daylight Time (IDT) are 2 hours
2598 ahead of the prime meridian in winter, springing forward an hour on
2599 March's fourth Thursday at 26:00 (i.e., 02:00 on the first Friday on or
2600 after March 23), and falling back on October's last Sunday at 02:00.
2603 IST-2IDT,M3.4.4/26,M10.5.0
2606 Western Argentina Summer Time (WARST) is 3 hours behind the prime
2607 meridian all year. There is a dummy fall-back transition on December
2608 31 at 25:00 daylight saving time (i.e., 24:00 standard time,
2609 equivalent to January 1 at 00:00 standard time), and a simultaneous
2610 spring-forward transition on January 1 at 00:00 standard time, so
2611 daylight saving time is in effect all year and the initial @code{WART}
2615 WART4WARST,J1/0,J365/25
2618 Western Greenland Time (WGT) and Western Greenland Summer Time (WGST)
2619 are 3 hours behind UTC in the winter. Its clocks follow the European
2620 Union rules of springing forward by one hour on March's last Sunday at
2621 01:00 UTC (@minus{}02:00 local time) and falling back on October's
2622 last Sunday at 01:00 UTC (@minus{}01:00 local time).
2625 WGT3WGST,M3.5.0/-2,M10.5.0/-1
2628 The schedule of Daylight Saving Time in any particular jurisdiction has
2629 changed over the years. To be strictly correct, the conversion of dates
2630 and times in the past should be based on the schedule that was in effect
2631 then. However, this format has no facilities to let you specify how the
2632 schedule has changed from year to year. The most you can do is specify
2633 one particular schedule---usually the present day schedule---and this is
2634 used to convert any date, no matter when. For precise time zone
2635 specifications, it is best to use the time zone information database
2638 The third format looks like this:
2644 Each operating system interprets this format differently; in
2645 @theglibc{}, @var{characters} is the name of a file which describes the time
2648 @pindex /etc/localtime
2650 If the @code{TZ} environment variable does not have a value, the
2651 operation chooses a time zone by default. In @theglibc{}, the
2652 default time zone is like the specification @samp{TZ=:/etc/localtime}
2653 (or @samp{TZ=:/usr/local/etc/localtime}, depending on how @theglibc{}
2654 was configured; @pxref{Installation}). Other C libraries use their own
2655 rule for choosing the default time zone, so there is little we can say
2658 @cindex time zone database
2659 @pindex /usr/share/zoneinfo
2661 If @var{characters} begins with a slash, it is an absolute file name;
2662 otherwise the library looks for the file
2663 @w{@file{/usr/share/zoneinfo/@var{characters}}}. The @file{zoneinfo}
2664 directory contains data files describing local time zones in many
2665 different parts of the world. The names represent major cities, with
2666 subdirectories for geographical areas; for example,
2667 @file{America/New_York}, @file{Europe/London}, @file{Asia/Hong_Kong}.
2668 These data files are installed by the system administrator, who also
2669 sets @file{/etc/localtime} to point to the data file for the local time
2670 zone. The files typically come from the @url{http://www.iana.org/time-zones,
2671 Time Zone Database} of time zone and daylight saving time
2672 information for most regions of the world, which is maintained by a
2673 community of volunteers and put in the public domain.
2675 @node Time Zone Functions
2676 @subsection Functions and Variables for Time Zones
2678 @deftypevar {char *} tzname [2]
2679 @standards{POSIX.1, time.h}
2680 The array @code{tzname} contains two strings, which are the standard
2681 names of the pair of time zones (standard and Daylight
2682 Saving) that the user has selected. @code{tzname[0]} is the name of
2683 the standard time zone (for example, @code{"EST"}), and @code{tzname[1]}
2684 is the name for the time zone when Daylight Saving Time is in use (for
2685 example, @code{"EDT"}). These correspond to the @var{std} and @var{dst}
2686 strings (respectively) from the @code{TZ} environment variable. If
2687 Daylight Saving Time is never used, @code{tzname[1]} is the empty string.
2689 The @code{tzname} array is initialized from the @code{TZ} environment
2690 variable whenever @code{tzset}, @code{ctime}, @code{strftime},
2691 @code{mktime}, or @code{localtime} is called. If multiple abbreviations
2692 have been used (e.g. @code{"EWT"} and @code{"EDT"} for U.S. Eastern War
2693 Time and Eastern Daylight Time), the array contains the most recent
2696 The @code{tzname} array is required for POSIX.1 compatibility, but in
2697 GNU programs it is better to use the @code{tm_zone} member of the
2698 broken-down time structure, since @code{tm_zone} reports the correct
2699 abbreviation even when it is not the latest one.
2701 Though the strings are declared as @code{char *} the user must refrain
2702 from modifying these strings. Modifying the strings will almost certainly
2707 @deftypefun void tzset (void)
2708 @standards{POSIX.1, time.h}
2709 @safety{@prelim{}@mtsafe{@mtsenv{} @mtslocale{}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
2710 @c tzset @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2711 @c libc_lock_lock dup @asulock @aculock
2712 @c tzset_internal dup @mtsenv @mtslocale @ascuheap @asulock @aculock @acsmem @acsfd
2713 @c libc_lock_unlock dup @aculock
2714 The @code{tzset} function initializes the @code{tzname} variable from
2715 the value of the @code{TZ} environment variable. It is not usually
2716 necessary for your program to call this function, because it is called
2717 automatically when you use the other time conversion functions that
2718 depend on the time zone.
2721 The following variables are defined for compatibility with System V
2722 Unix. Like @code{tzname}, these variables are set by calling
2723 @code{tzset} or the other time conversion functions.
2725 @deftypevar {long int} timezone
2726 @standards{SVID, time.h}
2727 This contains the difference between UTC and the latest local standard
2728 time, in seconds west of UTC. For example, in the U.S. Eastern time
2729 zone, the value is @code{5*60*60}. Unlike the @code{tm_gmtoff} member
2730 of the broken-down time structure, this value is not adjusted for
2731 daylight saving, and its sign is reversed. In GNU programs it is better
2732 to use @code{tm_gmtoff}, since it contains the correct offset even when
2733 it is not the latest one.
2736 @deftypevar int daylight
2737 @standards{SVID, time.h}
2738 This variable has a nonzero value if Daylight Saving Time rules apply.
2739 A nonzero value does not necessarily mean that Daylight Saving Time is
2740 now in effect; it means only that Daylight Saving Time is sometimes in
2744 @node Time Functions Example
2745 @subsection Time Functions Example
2747 Here is an example program showing the use of some of the calendar time
2751 @include strftim.c.texi
2754 It produces output like this:
2757 Wed Jul 31 13:02:36 1991
2758 Today is Wednesday, July 31.
2759 The time is 01:02 PM.
2763 @node Setting an Alarm
2764 @section Setting an Alarm
2766 The @code{alarm} and @code{setitimer} functions provide a mechanism for a
2767 process to interrupt itself in the future. They do this by setting a
2768 timer; when the timer expires, the process receives a signal.
2770 @cindex setting an alarm
2771 @cindex interval timer, setting
2772 @cindex alarms, setting
2773 @cindex timers, setting
2774 Each process has three independent interval timers available:
2778 A real-time timer that counts elapsed time. This timer sends a
2779 @code{SIGALRM} signal to the process when it expires.
2780 @cindex real-time timer
2781 @cindex timer, real-time
2784 A virtual timer that counts processor time used by the process. This timer
2785 sends a @code{SIGVTALRM} signal to the process when it expires.
2786 @cindex virtual timer
2787 @cindex timer, virtual
2790 A profiling timer that counts both processor time used by the process,
2791 and processor time spent in system calls on behalf of the process. This
2792 timer sends a @code{SIGPROF} signal to the process when it expires.
2793 @cindex profiling timer
2794 @cindex timer, profiling
2796 This timer is useful for profiling in interpreters. The interval timer
2797 mechanism does not have the fine granularity necessary for profiling
2799 @c @xref{profil} !!!
2802 You can only have one timer of each kind set at any given time. If you
2803 set a timer that has not yet expired, that timer is simply reset to the
2806 You should establish a handler for the appropriate alarm signal using
2807 @code{signal} or @code{sigaction} before issuing a call to
2808 @code{setitimer} or @code{alarm}. Otherwise, an unusual chain of events
2809 could cause the timer to expire before your program establishes the
2810 handler. In this case it would be terminated, since termination is the
2811 default action for the alarm signals. @xref{Signal Handling}.
2813 To be able to use the alarm function to interrupt a system call which
2814 might block otherwise indefinitely it is important to @emph{not} set the
2815 @code{SA_RESTART} flag when registering the signal handler using
2816 @code{sigaction}. When not using @code{sigaction} things get even
2817 uglier: the @code{signal} function has fixed semantics with respect
2818 to restarts. The BSD semantics for this function is to set the flag.
2819 Therefore, if @code{sigaction} for whatever reason cannot be used, it is
2820 necessary to use @code{sysv_signal} and not @code{signal}.
2822 The @code{setitimer} function is the primary means for setting an alarm.
2823 This facility is declared in the header file @file{sys/time.h}. The
2824 @code{alarm} function, declared in @file{unistd.h}, provides a somewhat
2825 simpler interface for setting the real-time timer.
2829 @deftp {Data Type} {struct itimerval}
2830 @standards{BSD, sys/time.h}
2831 This structure is used to specify when a timer should expire. It contains
2832 the following members:
2834 @item struct timeval it_interval
2835 This is the period between successive timer interrupts. If zero, the
2836 alarm will only be sent once.
2838 @item struct timeval it_value
2839 This is the period between now and the first timer interrupt. If zero,
2840 the alarm is disabled.
2843 The @code{struct timeval} data type is described in @ref{Time Types}.
2846 @deftypefun int setitimer (int @var{which}, const struct itimerval *@var{new}, struct itimerval *@var{old})
2847 @standards{BSD, sys/time.h}
2848 @safety{@prelim{}@mtsafe{@mtstimer{}}@assafe{}@acsafe{}}
2849 @c This function is marked with @mtstimer because the same set of timers
2850 @c is shared by all threads of a process, so calling it in one thread
2851 @c may interfere with timers set by another thread. This interference
2852 @c is not regarded as destructive, because the interface specification
2853 @c makes this overriding while returning the previous value the expected
2854 @c behavior, and the kernel will serialize concurrent calls so that the
2855 @c last one prevails, with each call getting the timer information from
2856 @c the timer installed by the previous call in that serialization.
2857 The @code{setitimer} function sets the timer specified by @var{which}
2858 according to @var{new}. The @var{which} argument can have a value of
2859 @code{ITIMER_REAL}, @code{ITIMER_VIRTUAL}, or @code{ITIMER_PROF}.
2861 If @var{old} is not a null pointer, @code{setitimer} returns information
2862 about any previous unexpired timer of the same kind in the structure it
2865 The return value is @code{0} on success and @code{-1} on failure. The
2866 following @code{errno} error conditions are defined for this function:
2870 The timer period is too large.
2874 @deftypefun int getitimer (int @var{which}, struct itimerval *@var{old})
2875 @standards{BSD, sys/time.h}
2876 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
2877 The @code{getitimer} function stores information about the timer specified
2878 by @var{which} in the structure pointed at by @var{old}.
2880 The return value and error conditions are the same as for @code{setitimer}.
2885 @standards{BSD, sys/time.h}
2886 This constant can be used as the @var{which} argument to the
2887 @code{setitimer} and @code{getitimer} functions to specify the real-time
2890 @item ITIMER_VIRTUAL
2891 @standards{BSD, sys/time.h}
2892 This constant can be used as the @var{which} argument to the
2893 @code{setitimer} and @code{getitimer} functions to specify the virtual
2897 @standards{BSD, sys/time.h}
2898 This constant can be used as the @var{which} argument to the
2899 @code{setitimer} and @code{getitimer} functions to specify the profiling
2903 @deftypefun {unsigned int} alarm (unsigned int @var{seconds})
2904 @standards{POSIX.1, unistd.h}
2905 @safety{@prelim{}@mtsafe{@mtstimer{}}@assafe{}@acsafe{}}
2906 @c Wrapper for setitimer.
2907 The @code{alarm} function sets the real-time timer to expire in
2908 @var{seconds} seconds. If you want to cancel any existing alarm, you
2909 can do this by calling @code{alarm} with a @var{seconds} argument of
2912 The return value indicates how many seconds remain before the previous
2913 alarm would have been sent. If there was no previous alarm, @code{alarm}
2917 The @code{alarm} function could be defined in terms of @code{setitimer}
2922 alarm (unsigned int seconds)
2924 struct itimerval old, new;
2925 new.it_interval.tv_usec = 0;
2926 new.it_interval.tv_sec = 0;
2927 new.it_value.tv_usec = 0;
2928 new.it_value.tv_sec = (long int) seconds;
2929 if (setitimer (ITIMER_REAL, &new, &old) < 0)
2932 return old.it_value.tv_sec;
2936 There is an example showing the use of the @code{alarm} function in
2937 @ref{Handler Returns}.
2939 If you simply want your process to wait for a given number of seconds,
2940 you should use the @code{sleep} function. @xref{Sleeping}.
2942 You shouldn't count on the signal arriving precisely when the timer
2943 expires. In a multiprocessing environment there is typically some
2944 amount of delay involved.
2946 @strong{Portability Note:} The @code{setitimer} and @code{getitimer}
2947 functions are derived from BSD Unix, while the @code{alarm} function is
2948 specified by the POSIX.1 standard. @code{setitimer} is more powerful than
2949 @code{alarm}, but @code{alarm} is more widely used.
2954 The function @code{sleep} gives a simple way to make the program wait
2955 for a short interval. If your program doesn't use signals (except to
2956 terminate), then you can expect @code{sleep} to wait reliably throughout
2957 the specified interval. Otherwise, @code{sleep} can return sooner if a
2958 signal arrives; if you want to wait for a given interval regardless of
2959 signals, use @code{select} (@pxref{Waiting for I/O}) and don't specify
2960 any descriptors to wait for.
2961 @c !!! select can get EINTR; using SA_RESTART makes sleep win too.
2963 @deftypefun {unsigned int} sleep (unsigned int @var{seconds})
2964 @standards{POSIX.1, unistd.h}
2965 @safety{@prelim{}@mtunsafe{@mtascusig{:SIGCHLD/linux}}@asunsafe{}@acunsafe{}}
2966 @c On Mach, it uses ports and calls time. On generic posix, it calls
2967 @c nanosleep. On Linux, it temporarily blocks SIGCHLD, which is MT- and
2968 @c AS-Unsafe, and in a way that makes it AC-Unsafe (C-unsafe, even!).
2969 The @code{sleep} function waits for @var{seconds} seconds or until a signal
2970 is delivered, whichever happens first.
2972 If @code{sleep} returns because the requested interval is over,
2973 it returns a value of zero. If it returns because of delivery of a
2974 signal, its return value is the remaining time in the sleep interval.
2976 The @code{sleep} function is declared in @file{unistd.h}.
2979 Resist the temptation to implement a sleep for a fixed amount of time by
2980 using the return value of @code{sleep}, when nonzero, to call
2981 @code{sleep} again. This will work with a certain amount of accuracy as
2982 long as signals arrive infrequently. But each signal can cause the
2983 eventual wakeup time to be off by an additional second or so. Suppose a
2984 few signals happen to arrive in rapid succession by bad luck---there is
2985 no limit on how much this could shorten or lengthen the wait.
2987 Instead, compute the calendar time at which the program should stop
2988 waiting, and keep trying to wait until that calendar time. This won't
2989 be off by more than a second. With just a little more work, you can use
2990 @code{select} and make the waiting period quite accurate. (Of course,
2991 heavy system load can cause additional unavoidable delays---unless the
2992 machine is dedicated to one application, there is no way you can avoid
2995 On some systems, @code{sleep} can do strange things if your program uses
2996 @code{SIGALRM} explicitly. Even if @code{SIGALRM} signals are being
2997 ignored or blocked when @code{sleep} is called, @code{sleep} might
2998 return prematurely on delivery of a @code{SIGALRM} signal. If you have
2999 established a handler for @code{SIGALRM} signals and a @code{SIGALRM}
3000 signal is delivered while the process is sleeping, the action taken
3001 might be just to cause @code{sleep} to return instead of invoking your
3002 handler. And, if @code{sleep} is interrupted by delivery of a signal
3003 whose handler requests an alarm or alters the handling of @code{SIGALRM},
3004 this handler and @code{sleep} will interfere.
3006 On @gnusystems{}, it is safe to use @code{sleep} and @code{SIGALRM} in
3007 the same program, because @code{sleep} does not work by means of
3010 @deftypefun int nanosleep (const struct timespec *@var{requested_time}, struct timespec *@var{remaining})
3011 @standards{POSIX.1, time.h}
3012 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
3013 @c On Linux, it's a syscall. On Mach, it calls gettimeofday and uses
3015 If resolution to seconds is not enough the @code{nanosleep} function can
3016 be used. As the name suggests the sleep interval can be specified in
3017 nanoseconds. The actual elapsed time of the sleep interval might be
3018 longer since the system rounds the elapsed time you request up to the
3019 next integer multiple of the actual resolution the system can deliver.
3021 @code{*@var{requested_time}} is the elapsed time of the interval you
3024 The function returns as @code{*@var{remaining}} the elapsed time left
3025 in the interval for which you requested to sleep. If the interval
3026 completed without getting interrupted by a signal, this is zero.
3028 @code{struct timespec} is described in @ref{Time Types}.
3030 If the function returns because the interval is over the return value is
3031 zero. If the function returns @math{-1} the global variable @code{errno}
3032 is set to the following values:
3036 The call was interrupted because a signal was delivered to the thread.
3037 If the @var{remaining} parameter is not the null pointer the structure
3038 pointed to by @var{remaining} is updated to contain the remaining
3042 The nanosecond value in the @var{requested_time} parameter contains an
3043 illegal value. Either the value is negative or greater than or equal to
3047 This function is a cancellation point in multi-threaded programs. This
3048 is a problem if the thread allocates some resources (like memory, file
3049 descriptors, semaphores or whatever) at the time @code{nanosleep} is
3050 called. If the thread gets canceled these resources stay allocated
3051 until the program ends. To avoid this calls to @code{nanosleep} should
3052 be protected using cancellation handlers.
3053 @c ref pthread_cleanup_push / pthread_cleanup_pop
3055 The @code{nanosleep} function is declared in @file{time.h}.