Date and Time
*************

This chapter describes functions for manipulating dates and times, including functions for determining what time it is and conversion between different time representations.

Time Basics
===========

Discussing time in a technical manual can be difficult because the word ``time'' in English refers to lots of different things.  In this manual, we use a rigorous terminology to avoid confusion, and the only thing we use the simple word ``time'' for is to talk about the abstract concept.

A calendar time, sometimes called ``absolute time'', is a point in the Earth's time continuum, for example June 9, 2024, at 13:50:06.5 Coordinated Universal Time (UTC). UTC, formerly called Greenwich Mean Time, is the primary time standard on Earth, and is the basis for civil time and time zones.

We don't speak of a ``date'', because that is inherent in a calendar time.

An interval is a contiguous part of the time continuum between two calendar times, for example the hour on June 9, 2024, between 13:00 and 14:00 UTC.

An elapsed time is the length of an interval, for example, 35 minutes.  People sometimes sloppily use the word ``interval'' to refer to the elapsed time of some interval.

An amount of time is a sum of elapsed times, which need not be of any specific intervals.  For example, the amount of time it takes to read a book might be 9 hours, independently of when and in how many sittings it is read.

A period is the elapsed time of an interval between two events, especially when they are part of a sequence of regularly repeating events.

A simple calendar time is a calendar time represented as an elapsed time since a fixed, implementation-specific calendar time called the epoch.  This representation is convenient for doing calculations on calendar times, such as finding the elapsed time between two calendar times.  Simple calendar times are independent of time zone; they represent the same instant in time regardless of where on the globe the computer is.

POSIX says that simple calendar times do not include leap seconds, but some (otherwise POSIX-conformant) systems can be configured to include leap seconds in simple calendar times.

A broken-down time is a calendar time represented by its components in the Gregorian calendar: year, month, day, hour, minute, and second.  A broken-down time value is relative to a specific time zone, and so it is also sometimes called a local time. Broken-down times are most useful for input and output, as they are easier for people to understand, but more difficult to calculate with.

A time zone is a single fixed offset from UTC, along with a time zone abbreviation that is a string of characters that can include ASCII alphanumerics, +, and -. For example, the current time zone in Japan is 9 hours ahead (east) of the Prime Meridian with abbreviation "JST".

A time zone ruleset maps each simple calendar time to a single time zone.  For example, Paris's time zone ruleset might list over a dozen time zones that Paris has experienced during its history.

CPU time measures the amount of time that a single process has actively used a CPU to perform computations.  It does not include the time that process has spent waiting for external events.  The system tracks the CPU time used by each process separately.

Processor time measures the amount of time any CPU has been in use by any process.  It is a basic system resource, since there's a limit to how much can exist in any given interval (the elapsed time of the interval times the number of CPUs in the computer)

People often call this CPU time, but we reserve the latter term in this manual for the definition above.

Time Types
==========

ISO C and POSIX define several data types for representing elapsed times, simple calendar times, and broken-down times.

 -- Data Type: clock_t
     ISO, time.h clock_t is used to measure processor and CPU time. It may be an integer or a floating-point type. Its values are counts of clock ticks since some arbitrary event in the past. The number of clock ticks per second is system-specific. See Processor And CPU Time, for further detail.

 -- Data Type: time_t
     ISO, time.h time_t is the simplest data type used to represent simple calendar time.

     In ISO C, time_t can be either an integer or a real floating type, and the meaning of time_t values is not specified.  The only things a strictly conforming program can do with time_t values are: pass them to difftime to get the elapsed time between two simple calendar times (see Calculating Elapsed Time), and pass them to the functions that convert them to broken-down time (see Broken-down Time).

     On POSIX-conformant systems, time_t is an integer type and its values represent the number of seconds elapsed since the POSIX Epoch, which is January 1, 1970, at 00:00:00 Coordinated Universal Time (UTC). The count of seconds ignores leap seconds.  Additionally, POSIX.1-2024 added the requirement that time_t be at least 64 bits wide.

     Theglibc additionally guarantees that time_t is a signed type, and that all of its functions operate correctly on negative time_t values, which are interpreted as times before the POSIX Epoch. Functions like localtime assume the Gregorian calendar and UTC even though this is historically inaccurate for dates before 1582, for times before 1960, and for timestamps after the Gregorian calendar and UTC will become obsolete. Theglibc also supports leap seconds as an option, in which case time_t counts leap seconds instead of ignoring them. Currently the time_t type is 64 bits wide on all platforms supported by theglibc, except that it is 32 bits wide on a few older platforms unless you define _TIME_BITS to 64. See Feature Test Macros.

 -- Data Type: struct timespec
     POSIX.1, time.h struct timespec represents a simple calendar time, or an elapsed time, with sub-second resolution.  It is declared in time.h and has the following members:

     time_t tv_sec
          The number of whole seconds elapsed since the epoch (for a simple calendar time) or since some other starting point (for an elapsed time).

     long int tv_nsec
          The number of nanoseconds elapsed since the time given by the tv_sec member.

          When struct timespec values are produced by glibcadj functions, the value in this field will always be greater than or equal to zero, and less than 1,000,000,000. When struct timespec values are supplied to glibcadj functions, the value in this field must be in the same range.

 -- Data Type: struct timeval
     BSD, sys/time.h struct timeval is an older type for representing a simple calendar time, or an elapsed time, with sub-second resolution. It is almost the same as struct timespec, but provides only microsecond resolution.  It is declared in sys/time.h and has the following members:

     time_t tv_sec
          The number of whole seconds elapsed since the epoch (for a simple calendar time) or since some other starting point (for an elapsed time).

     long int tv_usec
          The number of microseconds elapsed since the time given by the tv_sec member.

          When struct timeval values are produced by glibcadj functions, the value in this field will always be greater than or equal to zero, and less than 1,000,000. When struct timeval values are supplied to glibcadj functions, the value in this field must be in the same range.

 -- Data Type: struct tm
     ISO, time.h This is the data type used to represent a broken-down time.  It has separate fields for year, month, day, and so on. See Broken-down Time, for further details.

Calculating Elapsed Time
========================

Often, one wishes to calculate an elapsed time as the difference between two simple calendar times.  Theglibc provides only one function for this purpose.

 -- Function: double difftime (time_t END, time_t BEGIN)
     ISO, time.h The difftime function returns the number of seconds of elapsed time from calendar time BEGIN to calendar time END, as a value of type double.

     On POSIX-conformant systems, the advantage of using difftime (END, BEGIN) over END - BEGIN is that it will not overflow even if END and BEGIN are so far apart that a simple subtraction would overflow.  However, if they are so far apart that a double cannot exactly represent the difference, the result will be inexact.

     On other systems, time_t values might be encoded in a way that prevents subtraction from working directly, and then difftime would be the only way to compute their difference.

Theglibc does not provide any functions for computing the difference between two values of type struct timespec or struct timeval.  Here is one way to do this calculation by hand.  It works even on peculiar operating systems where the tv_sec member has an unsigned type.

          [file timespec_subtract.c.texi not included]

Processor And CPU Time
======================

If you're trying to optimize your program or measure its efficiency, it's very useful to know how much processor time it uses.  For that, calendar time and elapsed times are useless because a process may spend time waiting for I/O or for other processes to use the CPU.  However, you can get the information with the functions in this section.

CPU time (see Time Basics) is represented by the data type clock_t, which is a number of clock ticks.  It gives the total amount of time a process has actively used a CPU since some arbitrary event.  On gnusystems, that event is the creation of the process.  While arbitrary in general, the event is always the same event for any particular process, so you can always measure how much time on the CPU a particular computation takes by examining the process' CPU time before and after the computation.

 -- Macro: CLOCKS_PER_SEC
     ISO, time.h The number of clock ticks per second.

On gnulinuxhurdsystems, clock_t is equivalent to long int and CLOCKS_PER_SEC is an integer value.  But in other systems, both clock_t and the macro CLOCKS_PER_SEC can be either integer or floating-point types.  Converting CPU time values to double can help code be more portable no matter what the underlying representation is.

Note that the clock can wrap around.  On a 32bit system with CLOCKS_PER_SEC set to one million this function will return the same value approximately every 72 minutes.

For additional functions to examine a process' use of processor time, and to control it, see Resource Usage And Limitation.

CPU Time Inquiry
----------------

To get a process' CPU time, you can use the clock function.  This facility is declared in the header file time.h.

In typical usage, you call the clock function at the beginning and end of the interval you want to time, subtract the values, and then divide by CLOCKS_PER_SEC (the number of clock ticks per second) to get processor time, like this:

     #include <time.h>

     clock_t start, end;
     double cpu_time_used;

     start = clock();
     ... /* Do the work. */
     end = clock();
     cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

Do not use a single CPU time as an amount of time; it doesn't work that way.  Either do a subtraction as shown above or query processor time directly.  See Processor Time.

Different computers and operating systems vary wildly in how they keep track of CPU time.  It's common for the internal processor clock to have a resolution somewhere between a hundredth and millionth of a second.

 -- Macro: int CLOCKS_PER_SEC
     ISO, time.h The value of this macro is the number of clock ticks per second measured by the clock function.  POSIX requires that this value be one million independent of the actual resolution.

 -- Function: clock_t clock (void)
     ISO, time.h This function returns the calling process' current CPU time.  If the CPU time is not available or cannot be represented, clock returns the value (clock_t)(-1).

Processor Time Inquiry
----------------------

The times function returns information about a process' consumption of processor time in a struct tms object, in addition to the process' CPU time.  See Time Basics.  You should include the header file sys/times.h to use this facility.

 -- Data Type: struct tms
     POSIX.1, sys/times.h The tms structure is used to return information about process times.  It contains at least the following members:

     clock_t tms_utime
          This is the total processor time the calling process has used in executing the instructions of its program.

     clock_t tms_stime
          This is the processor time the system has used on behalf of the calling process.

     clock_t tms_cutime
          This is the sum of the tms_utime values and the tms_cutime values of all terminated child processes of the calling process, whose status has been reported to the parent process by wait or waitpid; see Process Completion.  In other words, it represents the total processor time used in executing the instructions of all the terminated child processes of the calling process, excluding child processes which have not yet been reported by wait or waitpid.

     clock_t tms_cstime
          This is similar to tms_cutime, but represents the total processor time the system has used on behalf of all the terminated child processes of the calling process.

     All of the times are given in numbers of clock ticks.  Unlike CPU time, these are the actual amounts of time; not relative to any event. See Creating a Process.

 -- Macro: int CLK_TCK
     POSIX.1, time.h This is an obsolete name for the number of clock ticks per second.  Use sysconf (_SC_CLK_TCK) instead.

 -- Function: clock_t times (struct tms *BUFFER)
     POSIX.1, sys/times.h The times function stores the processor time information for the calling process in BUFFER.

     The return value is the number of clock ticks since an arbitrary point in the past, e.g. since system start-up.  times returns (clock_t)(-1) to indicate failure.

Portability Note: The clock function described in CPU Time is specified by the ISO C standard.  The times function is a feature of POSIX.1.  On gnusystems, the CPU time is defined to be equivalent to the sum of the tms_utime and tms_stime fields returned by times.

Calendar Time
=============

This section describes the functions for getting, setting, and manipulating calendar times.

Getting the Time
----------------

Theglibc provides several functions for getting the current calendar time, with different levels of resolution.

 -- Function: time_t time (time_t *RESULT)
     ISO, time.h This is the simplest function for getting the current calendar time. It returns the calendar time as a value of type time_t; on POSIX systems, that means it has a resolution of one second.  It uses the same clock as clock_gettime (CLOCK_REALTIME_COARSE), when the clock is available or clock_gettime (CLOCK_REALTIME) otherwise.

     If the argument RESULT is not a null pointer, the calendar time value is also stored in *RESULT.

     This function cannot fail.

Some applications need more precise timekeeping than is possible with a time_t alone.  Some applications also need more control over what is meant by ``the current time.''  For these applications, POSIX and ISO C provide functions to retrieve the time with up to nanosecond precision, from a variety of different clocks. Clocks can be system-wide, measuring time the same for all processes; or they can be per-process or per-thread, measuring CPU time consumed by a particular process, or some other similar resource.  Each clock has its own resolution and epoch.  POSIX and ISO C also provide functions for finding the resolution of a clock.  There is no function to get the epoch for a clock; either it is fixed and documented, or the clock is not meant to be used to measure absolute times.

 -- Data Type: clockid_t
     POSIX.1, time.h The type clockid_t is used for constants that indicate which of several POSIX system clocks one wishes to use.

All systems that support the POSIX functions will define at least this clock constant:

 -- Macro: clockid_t CLOCK_REALTIME
     POSIX.1, time.h This POSIX clock uses the POSIX Epoch, 1970-01-01 00:00:00 UTC. It is close to, but not necessarily in lock-step with, the clocks of time (above) and of gettimeofday (below).

A second clock constant which is not universal, but still very common, is for a clock measuring monotonic time.  Monotonic time is useful for measuring elapsed times, because it guarantees that those measurements are not affected by changes to the system clock.

 -- Macro: clockid_t CLOCK_MONOTONIC
     POSIX.1, time.h This system-wide POSIX clock continuously measures the advancement of calendar time, ignoring discontinuous changes to the system's setting for absolute calendar time.

     The epoch for this clock is an unspecified point in the past. The epoch may change if the system is rebooted or suspended. Therefore, CLOCK_MONOTONIC cannot be used to measure absolute time, only elapsed time.

The following clocks are defined by POSIX, but may not be supported by all POSIX systems:

 -- Macro: clockid_t CLOCK_PROCESS_CPUTIME_ID
     POSIX.1, time.h This POSIX clock measures the amount of CPU time used by the calling process.

 -- Macro: clockid_t CLOCK_THREAD_CPUTIME_ID
     POSIX.1, time.h This POSIX clock measures the amount of CPU time used by the calling thread.

The following clocks are Linux extensions:

 -- Macro: clockid_t CLOCK_MONOTONIC_RAW
 -- Macro: clockid_t CLOCK_REALTIME_COARSE
 -- Macro: clockid_t CLOCK_MONOTONIC_COARSE
 -- Macro: clockid_t CLOCK_BOOTTIME
 -- Macro: clockid_t CLOCK_REALTIME_ALARM
 -- Macro: clockid_t CLOCK_BOOTTIME_ALARM
 -- Macro: clockid_t CLOCK_TAI
     Linux, time.h For details of these clocks, see the manual page clock_gettime,2.

Systems may support additional clocks beyond those listed here.

 -- Function: int clock_gettime (clockid_t CLOCK, struct timespec *TS)
     POSIX.1, time.h Get the current time according to the clock identified by CLOCK, storing it as seconds and nanoseconds in *TS. See Time Types, for a description of struct timespec.

     The return value is 0 on success and -1 on failure.  The following errno error condition is defined for this function:

     EINVAL
          The clock identified by CLOCK is not supported.

clock_gettime reports the time scaled to seconds and nanoseconds, but the actual resolution of each clock may not be as fine as one nanosecond, and may not be the same for all clocks.  POSIX also provides a function for finding out the actual resolution of a clock:

 -- Function: int clock_getres (clockid_t CLOCK, struct timespec *RES)
     POSIX.1, time.h Get the actual resolution of the clock identified by CLOCK, storing it in *TS.

     For instance, if the clock hardware for CLOCK_REALTIME uses a quartz crystal that oscillates at 32.768 kHz, then its resolution would be 30.518 microseconds, and clock_getres (CLOCK_REALTIME, &r) would set r.tv_sec to 0 and r.tv_nsec to 30518.

     The return value is 0 on success and -1 on failure.  The following errno error condition is defined for this function:

     EINVAL
          The clock identified by CLOCK is not supported.

Portability Note: On some systems, including systems that use older versions of theglibc, programs that use clock_gettime or clock_setres must be linked with the -lrt library. This has not been necessary with theglibc since version 2.17.

The following ISO C macros and functions for higher-resolution timestamps were standardized more recently than the POSIX functions, so they are less portable to older POSIX systems.  However, the ISO C functions are portable to C platforms that do not support POSIX.

 -- Macro: int TIME_UTC
     ISO, time.h This is a positive integer constant designating a simple calendar time base. In theglibc and other POSIX systems, this is equivalent to the POSIX CLOCK_REALTIME clock. On non-POSIX systems, though, the epoch is implementation-defined.

Systems may support more than just this ISO C clock.

 -- Function: int timespec_get (struct timespec *TS, int BASE)
     ISO, time.h Store into *TS the current time according to the ISO C time BASE.

     The return value is BASE on success and 0 on failure.

 -- Function: int timespec_getres (struct timespec *RES, int BASE)
     ISO, time.h If TS is non-null, store into *TS the resolution of the time provided by timespec_get function for the ISO C time BASE.

     The return value is BASE on success and 0 on failure.

The previous functions, data types and constants are declared in time.h. Theglibc also provides an older function for getting the current time with a resolution of microseconds.  This function is declared in sys/time.h.

 -- Function: int gettimeofday (struct timeval *TP, void *TZP)
     BSD, sys/time.h Get the current calendar time, storing it as seconds and microseconds in *TP.  See Time Types, for a description of struct timeval.  The clock of gettimeofday is close to, but not necessarily in lock-step with, the clocks of time and of clock_gettime (CLOCK_REALTIME) (see above).

     On some historic systems, if TZP was not a null pointer, information about a system-wide time zone would be written to *TZP.  This feature is obsolete and not supported on gnusystems.  You should always supply a null pointer for this argument.  Instead, use the facilities described in Broken-down Time for working with time zones.

     This function cannot fail, and its return value is always 0.

     Portability Note: POSIX.1-2024 removed this function. Although theglibc will continue to provide it indefinitely, portable programs should use clock_gettime or timespec_get instead.

Setting and Adjusting the Time
------------------------------

The clock hardware inside a modern computer is quite reliable, but it can still be wrong.  The functions in this section allow one to set the system's idea of the current calendar time, and to adjust the rate at which the system counts seconds, so that the calendar time will both be accurate, and remain accurate.

The functions in this section require special privileges to use. See Users and Groups.

 -- Function: int clock_settime (clockid_t CLOCK, const struct timespec *TS)
     POSIX, time.h Change the current calendar time, according to the clock identified by CLOCK, to be the simple calendar time in *TS.

     Not all of the system's clocks can be changed.  For instance, the CLOCK_REALTIME clock can be changed (with the appropriate privileges), but the CLOCK_MONOTONIC clock cannot.

     Because simple calendar times are independent of time zone, this function should not be used when the time zone changes (e.g. if the computer is physically moved from one zone to another).  Instead, use the facilities described in Time Zone State.

     clock_settime causes the clock to jump forwards or backwards, which can cause a variety of problems.  Changing the CLOCK_REALTIME clock with clock_settime does not affect when timers expire (see Setting an Alarm) or when sleeping processes wake up (see Sleeping), which avoids some of the problems.  Still, for small changes made while the system is running, it is better to use ntp_adjtime (below) to make a smooth transition from one time to another.

     The return value is 0 on success and -1 on failure.  The following errno error conditions are defined for this function:

     EINVAL
          The clock identified by CLOCK is not supported or cannot be set at all, or the simple calendar time in *TS is invalid (for instance, ts->tv_nsec is negative or greater than 999,999,999).

     EPERM
          This process does not have the privileges required to set the clock identified by CLOCK.

     Portability Note: On some systems, including systems that use older versions of theglibc, programs that use clock_settime must be linked with the -lrt library.  This has not been necessary with theglibc since version 2.17.

For systems that remain up and running for long periods, it is not enough to set the time once; one should also discipline the clock so that it does not drift away from the true calendar time.

The ntp_gettime and ntp_adjtime functions provide an interface to monitor and discipline the system clock.  For example, you can fine-tune the rate at which the clock ``ticks,'' and make small adjustments to the current reported calendar time smoothly, by temporarily speeding up or slowing down the clock.

These functions' names begin with ntp_ because they were designed for use by programs implementing the Network Time Protocol to synchronize a system's clock with other systems' clocks and/or with external high-precision clock hardware.

These functions, and the constants and structures they use, are declared in sys/timex.h.

 -- Data Type: struct ntptimeval
     This structure is used to report information about the system clock. It contains the following members:

     struct timeval time
          The current calendar time, as if retrieved by gettimeofday. The struct timeval data type is described in Time Types.

     long int maxerror
          This is the maximum error, measured in microseconds.  Unless updated via ntp_adjtime periodically, this value will reach some platform-specific maximum value.

     long int esterror
          This is the estimated error, measured in microseconds.  This value can be set by ntp_adjtime to indicate the estimated offset of the system clock from the true calendar time.

 -- Function: int ntp_gettime (struct ntptimeval *TPTR)
     GNU, sys/timex.h The ntp_gettime function sets the structure pointed to by TPTR to current values.  The elements of the structure afterwards contain the values the timer implementation in the kernel assumes.  They might or might not be correct.  If they are not, an ntp_adjtime call is necessary.

     The return value is 0 on success and other values on failure.  The following errno error conditions are defined for this function:

     TIME_ERROR
          The precision clock model is not properly set up at the moment, thus the clock must be considered unsynchronized, and the values should be treated with care.

 -- Data Type: struct timex
     This structure is used to control and monitor the system clock.  It contains the following members:

     unsigned int modes
          This variable controls whether and which values are set.  Several symbolic constants have to be combined with binary or to specify the effective mode.  These constants start with MOD_.

     long int offset
          This value indicates the current offset of the system clock from the true calendar time.  The value is given in microseconds.  If bit MOD_OFFSET is set in modes, the offset (and possibly other dependent values) can be set.  The offset's absolute value must not exceed MAXPHASE.

     long int frequency
          This value indicates the difference in frequency between the true calendar time and the system clock.  The value is expressed as scaled PPM (parts per million, 0.0001%).  The scaling is 1 << SHIFT_USEC.  The value can be set with bit MOD_FREQUENCY, but the absolute value must not exceed MAXFREQ.

     long int maxerror
          This is the maximum error, measured in microseconds.  A new value can be set using bit MOD_MAXERROR.  Unless updated via ntp_adjtime periodically, this value will increase steadily and reach some platform-specific maximum value.

     long int esterror
          This is the estimated error, measured in microseconds.  This value can be set using bit MOD_ESTERROR.

     int status
          This variable reflects the various states of the clock machinery.  There are symbolic constants for the significant bits, starting with STA_.  Some of these flags can be updated using the MOD_STATUS bit.

     long int constant
          This value represents the bandwidth or stiffness of the PLL (phase locked loop) implemented in the kernel.  The value can be changed using bit MOD_TIMECONST.

     long int precision
          This value represents the accuracy or the maximum error when reading the system clock.  The value is expressed in microseconds.

     long int tolerance
          This value represents the maximum frequency error of the system clock in scaled PPM.  This value is used to increase the maxerror every second.

     struct timeval time
          The current calendar time.

     long int tick
          The elapsed time between clock ticks in microseconds.  A clock tick is a periodic timer interrupt on which the system clock is based.

     long int ppsfreq
          This is the first of a few optional variables that are present only if the system clock can use a PPS (pulse per second) signal to discipline the system clock.  The value is expressed in scaled PPM and it denotes the difference in frequency between the system clock and the PPS signal.

     long int jitter
          This value expresses a median filtered average of the PPS signal's dispersion in microseconds.

     int shift
          This value is a binary exponent for the duration of the PPS calibration interval, ranging from PPS_SHIFT to PPS_SHIFTMAX.

     long int stabil
          This value represents the median filtered dispersion of the PPS frequency in scaled PPM.

     long int jitcnt
          This counter represents the number of pulses where the jitter exceeded the allowed maximum MAXTIME.

     long int calcnt
          This counter reflects the number of successful calibration intervals.

     long int errcnt
          This counter represents the number of calibration errors (caused by large offsets or jitter).

     long int stbcnt
          This counter denotes the number of calibrations where the stability exceeded the threshold.

 -- Function: int ntp_adjtime (struct timex *TPTR)
     GNU, sys/timex.h The ntp_adjtime function sets the structure specified by TPTR to current values.

     In addition, ntp_adjtime updates some settings to match what you pass to it in *TPTR.  Use the modes element of *TPTR to select what settings to update.  You can set offset, freq, maxerror, esterror, status, constant, and tick.

     modes = zero means set nothing.

     Only the superuser can update settings.

     The return value is 0 on success and other values on failure.  The following errno error conditions are defined for this function:

     TIME_ERROR
          The high accuracy clock model is not properly set up at the moment, thus the clock must be considered unsynchronized, and the values should be treated with care.  Another reason could be that the specified new values are not allowed.

     EPERM
          The process specified a settings update, but is not superuser.

     For more details see RFC 5905 (Network Time Protocol, Version 4) and related documents.

     Portability note: Early versions of theglibc did not have this function, but did have the synonymous adjtimex.

 -- Function: int adjtime (const struct timeval *DELTA, struct timeval *OLDDELTA)
     BSD, sys/time.h This simpler version of ntp_adjtime speeds up or slows down the system clock for a short time, in order to correct it by a small amount.  This avoids a discontinuous change in the calendar time reported by the CLOCK_REALTIME clock, at the price of having to wait longer for the time to become correct.

     The DELTA argument specifies a relative adjustment to be made to the clock time.  If negative, the system clock is slowed down for a while until it has lost this much elapsed time.  If positive, the system clock is sped up for a while.

     If the OLDDELTA argument is not a null pointer, the adjtime function returns information about any previous time adjustment that has not yet completed.

     The return value is 0 on success and -1 on failure.  The following errno error condition is defined for this function:

     EPERM
          This process does not have the privileges required to adjust the CLOCK_REALTIME clock.

For compatibility, theglibc also provides several older functions for controlling the system time.  New programs should prefer to use the functions above.

 -- Function: int stime (const time_t *NEWTIME)
     SVID, time.h XPG, time.h Change the CLOCK_REALTIME calendar time to be the simple calendar time in *NEWTIME.  Calling this function is exactly the same as calling clock_settime (CLOCK_REALTIME), except that the new time can only be set to a precision of one second.

     This function is no longer available on gnusystems, but it may be the only way to set the time on very old Unix systems, so we continue to document it.  If it is available, it is declared in time.h.

     The return value is 0 on success and -1 on failure.  The following errno error condition is defined for this function:

     EPERM
          This process does not have the privileges required to adjust the CLOCK_REALTIME clock.

 -- Function: int adjtimex (struct timex *TIMEX)
     GNU, sys/timex.h adjtimex is an older name for ntp_adjtime. This function is only available on gnulinuxsystems. It is declared in sys/timex.h.

 -- Function: int settimeofday (const struct timeval *TP, const void *TZP)
     BSD, sys/time.h Change the CLOCK_REALTIME calendar time to be the simple calendar time in *NEWTIME.  This function is declared in sys/time.h.

     When TZP is a null pointer, calling this function is exactly the same as calling clock_settime (CLOCK_REALTIME), except that the new time can only be set to a precision of one microsecond.

     When TZP is not a null pointer, the data it points to may be used to set a system-wide idea of the current time zone.  This feature is obsolete and not supported on gnusystems.  Instead, use the facilities described in Time Zone State and in Broken-down Time for working with time zones.

     The return value is 0 on success and -1 on failure.  The following errno error conditions are defined for this function:

     EPERM
          This process does not have the privileges required to set the CLOCK_REALTIME clock.

     EINVAL
          Neither TP nor TZP is a null pointer.  (For historical reasons, it is not possible to set the current time and the current time zone in the same call.)

     ENOSYS
          The operating system does not support setting time zone information, and TZP is not a null pointer.

Broken-down Time
----------------

Simple calendar times represent absolute times as elapsed times since an epoch.  This is convenient for computation, but has no relation to the way people normally think of calendar time.  By contrast, broken-down time is a binary representation of calendar time separated into year, month, day, and so on.  Although broken-down time values are painful to calculate with, they are useful for printing human readable time information.

A broken-down time value is always relative to a choice of time zone, and it also indicates which time zone that is.

The symbols in this section are declared in the header file time.h.

 -- Data Type: struct tm
     ISO, time.h This is the data type used to represent a broken-down time.  The structure contains at least the following members, which can appear in any order.

     int tm_sec
          This is the number of full seconds since the top of the minute (normally in the range 0 through 59, but the actual upper limit is 60, to allow for leap seconds if leap second support is available).

     int tm_min
          This is the number of full minutes since the top of the hour (in the range 0 through 59).

     int tm_hour
          This is the number of full hours past midnight (in the range 0 through 23).

     int tm_mday
          This is the ordinal day of the month (in the range 1 through 31). Watch out for this one!  As the only ordinal number in the structure, it is inconsistent with the rest of the structure.

     int tm_mon
          This is the number of full calendar months since the beginning of the year (in the range 0 through 11).  Watch out for this one! People usually use ordinal numbers for month-of-year (where January = 1).

     int tm_year
          This is the number of full calendar years since 1900.

     int tm_wday
          This is the number of full days since Sunday (in the range 0 through 6).

     int tm_yday
          This is the number of full days since the beginning of the year (in the range 0 through 365).

     int tm_isdst
          This is a flag that indicates whether daylight saving time is (or was, or will be) in effect at the time described.  The value is positive if daylight saving time is in effect, zero if it is not, and negative if the information is not available. Although this flag is useful when passing a broken-down time to the mktime function, for other uses this flag should be ignored and the tm_gmtoff and tm_zone fields should be inspected instead.

     long int tm_gmtoff
          This field describes the time zone that was used to compute this broken-down time value, including any adjustment for daylight saving; it is the number of seconds that you must add to UTC to get local time. You can also think of this as the number of seconds east of the Prime Meridian. For example, for U.S. Eastern Standard Time, the value is -5*60*60.

     const char *tm_zone
          This field is the abbreviation for the time zone that was used to compute this broken-down time value.

     Portability note:  The tm_gmtoff and tm_zone fields are derived from BSD and are POSIX extensions to ISO C. Code intended to be portable to operating systems that lack these fields can instead use time zone state variables, although those variables are unreliable when the TZ environment variable has a geographical format.  See Time Zone State.

 -- Function: struct tm * localtime (const time_t *TIME)
     ISO, time.h prelim:tmbuf mtsenv mtslocale The localtime function converts the simple time pointed to by TIME to broken-down time representation, expressed relative to the user's specified time zone.

     The return value is a pointer to a static broken-down time structure, which might be overwritten by subsequent calls to gmtime or localtime.  (No other library function overwrites the contents of this object.)  In theglibc, the structure's tm_zone points to a string with a storage lifetime that lasts indefinitely; on other platforms, the lifetime may expire when the TZ environment variable is changed.

     The return value is the null pointer if TIME cannot be represented as a broken-down time; typically this is because the year cannot fit into an int.

     Calling localtime also sets the time zone state as if tzset were called.  See Time Zone State.

Using the localtime function is a big problem in multi-threaded programs.  The result is returned in a static buffer and this is used in all threads.  A variant function avoids this problem.

 -- Function: struct tm * localtime_r (const time_t *TIME, struct tm *RESULTP)
     POSIX.1c, time.h

     The localtime_r function works just like the localtime function.  It takes a pointer to a variable containing a simple time and converts it to the broken-down time format.

     But the result is not placed in a static buffer.  Instead it is placed in the object of type struct tm to which the parameter RESULTP points.  Also, the time zone state is not necessarily set as if tzset were called.

     If the conversion is successful the function returns a pointer to the object the result was written into, i.e., it returns RESULTP.

 -- Function: struct tm * gmtime (const time_t *TIME)
     ISO, time.h prelim:tmbuf mtsenv mtslocale This function is similar to localtime, except that the broken-down time is expressed as UTC rather than relative to a local time zone. The broken-down time's tm_gmtoff is 0, and its tm_zone is a string "UTC" with static storage duration.

As for the localtime function we have the problem that the result is placed in a static variable.  A thread-safe replacement is also provided for gmtime.

 -- Function: struct tm * gmtime_r (const time_t *TIME, struct tm *RESULTP)
     POSIX.1c, time.h This function is similar to localtime_r, except that it converts just like gmtime the given time as UTC.

     If the conversion is successful the function returns a pointer to the object the result was written into, i.e., it returns RESULTP.

 -- Function: time_t mktime (struct tm *BROKENTIME)
     ISO, time.h The mktime function converts a broken-down time structure to a simple time representation.  It also normalizes the contents of the broken-down time structure, and fills in some components based on the values of the others.

     The mktime function ignores the specified contents of the tm_wday, tm_yday, tm_gmtoff, and tm_zone members of the broken-down time structure.  It uses the values of the other components to determine the calendar time; it's permissible for these components to have unnormalized values outside their normal ranges.  The last thing that mktime does is adjust the components of the BROKENTIME structure, including the members that were initially ignored.

     If the specified broken-down time cannot be represented as a simple time, mktime returns a value of (time_t)(-1) and does not modify the contents of BROKENTIME.

     Calling mktime also sets the time zone state as if tzset were called; mktime uses this information instead of BROKENTIME's initial tm_gmtoff and tm_zone members.  See Time Zone State.

 -- Function: time_t timelocal (struct tm *BROKENTIME)
     ???, time.h

     timelocal is functionally identical to mktime, but more mnemonically named.  Note that it is the inverse of the localtime function.

     Portability note:  mktime is essentially universally available.  timelocal is rather rare.

 -- Function: time_t timegm (struct tm *BROKENTIME)
     ISO, time.h

     timegm is functionally identical to mktime except it always takes the input values to be UTC regardless of any local time zone setting.

     Note that timegm is the inverse of gmtime.

     Portability note:  mktime is essentially universally available.  Although timegm is standardized by C23, some other systems lack it; to be portable to them, you can set the TZ environment variable to UTC, call mktime, then set TZ back.

Formatting Calendar Time
------------------------

The functions described in this section format calendar time values as strings.  These functions are declared in the header file time.h.

 -- Function: size_t strftime (char *S, size_t SIZE, const char *TEMPLATE, const struct tm *BROKENTIME)
     ISO, time.h This function is similar to the sprintf function (see Formatted Input), but the conversion specifications that can appear in the format template TEMPLATE are specialized for printing components of BROKENTIME according to the locale currently specified for time conversion (see Locales) and the current time zone (see Time Zone State).

     Ordinary characters appearing in the TEMPLATE are copied to the output string S; this can include multibyte character sequences. Conversion specifiers are introduced by a % character, followed by an optional flag which can be one of the following.  These flags are all GNU extensions.  The first three affect only the output of numbers:

     _
          The number is padded with spaces.

     -
          The number is not padded at all.

     0
          The number is padded with zeros even if the format specifies padding with spaces.

     ^
          The output uses uppercase characters, but only if this is possible (see Case Conversion).

     The default action is to pad the number with zeros to keep it a constant width.  Numbers that do not have a range indicated below are never padded, since there is no natural width for them.

     Following the flag an optional specification of the width is possible. This is specified in decimal notation.  If the natural size of the output of the field has less than the specified number of characters, the result is written right adjusted and space padded to the given size.

     An optional modifier can follow the optional flag and width specification.  The modifiers are:

     E
          Use the locale's alternative representation for date and time.  This modifier applies to the %c, %C, %x, %X, %y and %Y format specifiers.  In a Japanese locale, for example, %Ex might yield a date format based on the Japanese Emperors' reigns.

     O
          With all format specifiers that produce numbers: use the locale's alternative numeric symbols.

          With %B, %b, and %h: use the grammatical form for month names that is appropriate when the month is named by itself, rather than the form that is appropriate when the month is used as part of a complete date.  The %OB and %Ob formats are a C23 feature, specified in C23 to use the locale's `alternative' month name; theglibc extends this specification to say that the form used in a complete date is the default and the form naming the month by itself is the alternative.

     If the format supports the modifier but no alternative representation is available, it is ignored.

     The conversion specifier ends with a format specifier taken from the following list.  The whole % sequence is replaced in the output string as follows:

     %a
          The abbreviated weekday name according to the current locale.

     %A
          The full weekday name according to the current locale.

     %b
          The abbreviated month name according to the current locale, in the grammatical form used when the month is part of a complete date. As a C23 feature (with a more detailed specification in theglibc), the O modifier can be used (%Ob) to get the grammatical form used when the month is named by itself.

     %B
          The full month name according to the current locale, in the grammatical form used when the month is part of a complete date. As a C23 feature (with a more detailed specification in theglibc), the O modifier can be used (%OB) to get the grammatical form used when the month is named by itself.

          Note that not all languages need two different forms of the month names, so the text produced by %B and %OB, and by %b and %Ob, may or may not be the same, depending on the locale.

     %c
          The preferred calendar time representation for the current locale.

     %C
          The century of the year.  This is equivalent to the greatest integer not greater than the year divided by 100.

          If the E modifier is specified (%EC), instead produces the name of the period for the year (e.g. an era name) in the locale's alternative calendar.

     %d
          The day of the month as a decimal number (range 01 through 31).

     %D
          The date using the format %m/%d/%y.

     %e
          The day of the month like with %d, but padded with spaces (range 1 through 31).

     %F
          The date using the format %Y-%m-%d.  This is the form specified in the ISO 8601 standard and is the preferred form for all uses.

     %g
          The year corresponding to the ISO week number, but without the century (range 00 through 99).  This has the same format and value as %y, except that if the ISO week number (see %V) belongs to the previous or next year, that year is used instead.

     %G
          The year corresponding to the ISO week number.  This has the same format and value as %Y, except that if the ISO week number (see %V) belongs to the previous or next year, that year is used instead.

     %h
          The abbreviated month name according to the current locale.  The action is the same as for %b.

     %H
          The hour as a decimal number, using a 24-hour clock (range 00 through 23).

     %I
          The hour as a decimal number, using a 12-hour clock (range 01 through 12).

     %j
          The day of the year as a decimal number (range 001 through 366).

     %k
          The hour as a decimal number, using a 24-hour clock like %H, but padded with spaces (range  0 through 23).

          This format is a GNU extension.

     %l
          The hour as a decimal number, using a 12-hour clock like %I, but padded with spaces (range  1 through 12).

          This format is a GNU extension.

     %m
          The month as a decimal number (range 01 through 12).

     %M
          The minute as a decimal number (range 00 through 59).

     %n
          A single \n (newline) character.

     %p
          Either AM or PM, according to the given time value; or the corresponding strings for the current locale.  Noon is treated as PM and midnight as AM.  In most locales AM/PM format is not supported, in such cases "%p" yields an empty string.

     %P
          Either am or pm, according to the given time value; or the corresponding strings for the current locale, printed in lowercase characters.  Noon is treated as pm and midnight as am.  In most locales AM/PM format is not supported, in such cases "%P" yields an empty string.

          This format is a GNU extension.

     %r
          The complete calendar time using the AM/PM format of the current locale.

          In the POSIX locale, this format is equivalent to %I:%M:%S %p.

     %R
          The hour and minute in decimal numbers using the format %H:%M.

     %s
          The number of seconds since the POSIX Epoch, i.e., since 1970-01-01 00:00:00 UTC. Leap seconds are not counted unless leap second support is available.

          This format is a GNU extension.

     %S
          The seconds as a decimal number (range 00 through 60).

     %t
          A single \t (tabulator) character.

     %T
          The time of day using decimal numbers using the format %H:%M:%S.

     %u
          The day of the week as a decimal number (range 1 through 7), Monday being 1.

     %U
          The week number of the current year as a decimal number (range 00 through 53), starting with the first Sunday as the first day of the first week.  Days preceding the first Sunday in the year are considered to be in week 00.

     %V
          The ISO 8601 week number as a decimal number (range 01 through 53).  ISO weeks start with Monday and end with Sunday. Week 01 of a year is the first week which has the majority of its days in that year; this is equivalent to the week containing the year's first Thursday, and it is also equivalent to the week containing January 4.  Week 01 of a year can contain days from the previous year. The week before week 01 of a year is the last week (52 or 53) of the previous year even if it contains days from the new year.

     %w
          The day of the week as a decimal number (range 0 through 6), Sunday being 0.

     %W
          The week number of the current year as a decimal number (range 00 through 53), starting with the first Monday as the first day of the first week.  All days preceding the first Monday in the year are considered to be in week 00.

     %x
          The preferred date representation for the current locale.

     %X
          The preferred time of day representation for the current locale.

     %y
          The year without a century as a decimal number (range 00 through 99).  This is equivalent to the year modulo 100.

          If the E modifier is specified (%Ey), instead produces the year number according to a locale-specific alternative calendar. Unlike %y, the number is not reduced modulo 100. However, by default it is zero-padded to a minimum of two digits (this can be overridden by an explicit field width or by the _ and - flags).

     %Y
          The year as a decimal number, using the Gregorian calendar.  Years before the year 1 are numbered 0, -1, and so on.

          If the E modifier is specified (%EY), instead produces a complete representation of the year according to the locale's alternative calendar.  Generally this will be some combination of the information produced by %EC and %Ey.  As a GNU extension, the formatting flags _ or - may be used with this conversion specifier; they affect how the year number is printed.

     %z
          RFC 5322/ISO 8601 style numeric time zone (e.g., -0600 or +0100), or nothing if no time zone is determinable.

          In the POSIX locale, a full RFC 5322 timestamp is generated by the format "%a, %d %b %Y %H:%M:%S %z" (or the equivalent "%a, %d %b %Y %T %z").

     %Z
          The time zone abbreviation (empty if the time zone can't be determined).

     %%
          A literal % character.

     The SIZE parameter can be used to specify the maximum number of characters to be stored in the array S, including the terminating null character.  If the formatted time requires more than SIZE characters, strftime returns zero and the contents of the array S are undefined.  Otherwise the return value indicates the number of characters placed in the array S, not including the terminating null character.

     Warning: This convention for the return value which is prescribed in ISO C can lead to problems in some situations.  For certain format strings and certain locales the output really can be the empty string and this cannot be discovered by testing the return value only. E.g., in most locales the AM/PM time format is not supported (most of the world uses the 24 hour time representation).  In such locales "%p" will return the empty string, i.e., the return value is zero.  To detect situations like this something similar to the following code should be used:

          buf[0] = '\1';
          len = strftime (buf, bufsize, format, tp);
          if (len == 0 && buf[0] != '\0')
            {
              /* Something went wrong in the strftime call.  */
              ...
            }

     If S is a null pointer, strftime does not actually write anything, but instead returns the number of characters it would have written.

     Calling strftime also sets the time zone state as if tzset were called.  See Time Zone State.

     For an example of strftime, see Time Functions Example.

 -- Function: size_t strftime_l (char *restrict S, size_t SIZE, const char *restrict TEMPLATE, const struct tm *BROKENTIME, locale_t LOCALE)
     POSIX.1, time.h The strftime_l function is equivalent to the strftime function except that it operates in LOCALE rather than in the current locale.

 -- Function: size_t wcsftime (wchar_t *S, size_t SIZE, const wchar_t *TEMPLATE, const struct tm *BROKENTIME)
     ISO, time.h The wcsftime function is equivalent to the strftime function with the difference that it operates on wide character strings.  The buffer where the result is stored, pointed to by S, must be an array of wide characters.  The parameter SIZE which specifies the size of the output buffer gives the number of wide characters, not the number of bytes.

     Also the format string TEMPLATE is a wide character string.  Since all characters needed to specify the format string are in the basic character set it is portably possible to write format strings in the C source code using the L"..." notation.  The parameter BROKENTIME has the same meaning as in the strftime call.

     The wcsftime function supports the same flags, modifiers, and format specifiers as the strftime function.

     The return value of wcsftime is the number of wide characters stored in s.  When more characters would have to be written than can be placed in the buffer S the return value is zero, with the same problems indicated in the strftime documentation.

 -- Deprecated function: char * asctime (const struct tm *BROKENTIME)
     ISO, time.h prelim:asctime mtslocale asunsafe acsafe The asctime function converts the broken-down time value that BROKENTIME points to into a string in a standard format:

          "Tue May 21 13:46:22 1991\n"

     The abbreviations for the days of week are: Sun, Mon, Tue, Wed, Thu, Fri, and Sat.

     The abbreviations for the months are: Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec.

     Behavior is undefined if the calculated year would be less than 1000 or greater than 9999.

     The return value points to a statically allocated string, which might be overwritten by subsequent calls to asctime or ctime. (No other library function overwrites the contents of this string.)

     Portability note: This obsolescent function is deprecated in C23. Programs should instead use strftime or even sprintf.

 -- Deprecated function: char * asctime_r (const struct tm *BROKENTIME, char *BUFFER)
     ???, time.h This function is similar to asctime but instead of placing the result in a static buffer it writes the string in the buffer pointed to by the parameter BUFFER.  This buffer should have room for at least 26 bytes, including the terminating null. Behavior is undefined if the calculated year would be less than 1000 or greater than 9999.

     If no error occurred the function returns a pointer to the string the result was written into, i.e., it returns BUFFER.  Otherwise it returns NULL.

     Portability Note: POSIX.1-2024 removed this obsolescent function. Programs should instead use strftime or even sprintf.

 -- Deprecated function: char * ctime (const time_t *TIME)
     ISO, time.h prelim:tmbuf :asctime mtsenv mtslocale The ctime function is similar to asctime, except that you specify the calendar time argument as a time_t simple time value rather than in broken-down local time format.  It is equivalent to

          asctime (localtime (TIME))

     Behavior is undefined if the calculated year would be less than 1000 or greater than 9999.

     Calling ctime also sets the time zone state as if tzset were called.  See Time Zone State.

     Portability note: This obsolescent function is deprecated in C23. Programs should instead use strftime or even sprintf.

 -- Deprecated function: char * ctime_r (const time_t *TIME, char *BUFFER)
     ???, time.h This function is similar to ctime, but places the result in the string pointed to by BUFFER, and the time zone state is not necessarily set as if tzset were called.  It is equivalent to:

          asctime_r (localtime_r (TIME, &(struct tm) {0}), BUFFER)

     Behavior is undefined if the calculated year would be less than 1000 or greater than 9999.

     If no error occurred the function returns a pointer to the string the result was written into, i.e., it returns BUFFER.  Otherwise it returns NULL.

     Portability Note: POSIX.1-2024 removed this obsolescent function. Programs should instead use strftime or even sprintf.

Convert textual time and date information back
----------------------------------------------

The ISO C standard does not specify any functions which can convert the output of the strftime function back into a binary format. This led to a variety of more-or-less successful implementations with different interfaces over the years.  Then the Unix standard was extended by the addition of two functions: strptime and getdate.  Both have strange interfaces but at least they are widely available.

Interpret string according to given format
..........................................

The first function is rather low-level.  It is nevertheless frequently used in software since it is better known.  Its interface and implementation are heavily influenced by the getdate function, which is defined and implemented in terms of calls to strptime.

 -- Function: char * strptime (const char *S, const char *FMT, struct tm *TP)
     XPG4, time.h The strptime function parses the input string S according to the format string FMT and stores its results in the structure TP.

     The input string could be generated by a strftime call or obtained any other way.  It does not need to be in a human-recognizable format; e.g. a date passed as "02:1999:9" is acceptable, even though it is ambiguous without context.  As long as the format string FMT matches the input string the function will succeed.

     The user has to make sure, though, that the input can be parsed in a unambiguous way.  The string "1999112" can be parsed using the format "%Y%m%d" as 1999-1-12, 1999-11-2, or even 19991-1-2.  It is necessary to add appropriate separators to reliably get results.

     The format string consists of the same components as the format string of the strftime function.  The only difference is that the flags _, -, 0, and ^ are not allowed. Several of the distinct formats of strftime do the same work in strptime since differences like case of the input do not matter. For reasons of symmetry all formats are supported, though.

     The modifiers E and O are also allowed everywhere the strftime function allows them.

     The formats are:

     %a
     %A
          The weekday name according to the current locale, in abbreviated form or the full name.

     %b
     %B
     %h
          A month name according to the current locale.  All three specifiers will recognize both abbreviated and full month names.  If the locale provides two different grammatical forms of month names, all three specifiers will recognize both forms.

          As a GNU extension, the O modifier can be used with these specifiers; it has no effect, as both grammatical forms of month names are recognized.

     %c
          The date and time representation for the current locale.

     %Ec
          Like %c but the locale's alternative date and time format is used.

     %C
          The century of the year.

          It makes sense to use this format only if the format string also contains the %y format.

     %EC
          The locale's representation of the period.

          Unlike %C it sometimes makes sense to use this format since some cultures represent years relative to the beginning of eras instead of using the Gregorian years.

     %d

     %e
          The day of the month as a decimal number (range 1 through 31). Leading zeroes are permitted but not required.

     %Od
     %Oe
          Same as %d but using the locale's alternative numeric symbols.

          Leading zeroes are permitted but not required.

     %D
          Equivalent to %m/%d/%y.

     %F
          Equivalent to %Y-%m-%d, which is the ISO 8601 date format.

          This is a GNU extension following an ISO C99 extension to strftime.

     %g
          The year corresponding to the ISO week number, but without the century (range 00 through 99).

          Note: Currently, this is not fully implemented.  The format is recognized, input is consumed but no field in TM is set.

          This format is a GNU extension following a GNU extension of strftime.

     %G
          The year corresponding to the ISO week number.

          Note: Currently, this is not fully implemented.  The format is recognized, input is consumed but no field in TM is set.

          This format is a GNU extension following a GNU extension of strftime.

     %H
     %k
          The hour as a decimal number, using a 24-hour clock (range 00 through 23).

          %k is a GNU extension following a GNU extension of strftime.

     %OH
          Same as %H but using the locale's alternative numeric symbols.

     %I
     %l
          The hour as a decimal number, using a 12-hour clock (range 01 through 12).

          %l is a GNU extension following a GNU extension of strftime.

     %OI
          Same as %I but using the locale's alternative numeric symbols.

     %j
          The day of the year as a decimal number (range 1 through 366).

          Leading zeroes are permitted but not required.

     %m
          The month as a decimal number (range 1 through 12).

          Leading zeroes are permitted but not required.

     %Om
          Same as %m but using the locale's alternative numeric symbols.

     %M
          The minute as a decimal number (range 0 through 59).

          Leading zeroes are permitted but not required.

     %OM
          Same as %M but using the locale's alternative numeric symbols.

     %n
     %t
          Matches any whitespace.

     %p

     %P
          The locale-dependent equivalent to AM or PM.

          This format is not useful unless %I or %l is also used. Another complication is that the locale might not define these values at all and therefore the conversion fails.

          %P is a GNU extension following a GNU extension to strftime.

     %r
          The complete time using the AM/PM format of the current locale.

          A complication is that the locale might not define this format at all and therefore the conversion fails.

     %R
          The hour and minute in decimal numbers using the format %H:%M.

          %R is a GNU extension following a GNU extension to strftime.

     %s
          The number of seconds since the POSIX Epoch, i.e., since 1970-01-01 00:00:00 UTC. Leap seconds are not counted unless leap second support is available.

          %s is a GNU extension following a GNU extension to strftime.

     %S
          The seconds as a decimal number (range 0 through 60).

          Leading zeroes are permitted but not required.

          NB: The Unix specification says the upper bound on this value is 61, a result of a decision to allow double leap seconds.  You will not see the value 61 because no minute has more than one leap second, but the myth persists.

     %OS
          Same as %S but using the locale's alternative numeric symbols.

     %T
          Equivalent to the use of %H:%M:%S in this place.

     %u
          The day of the week as a decimal number (range 1 through 7), Monday being 1.

          Leading zeroes are permitted but not required.

          Note: Currently, this is not fully implemented.  The format is recognized, input is consumed but no field in TM is set.

     %U
          The week number of the current year as a decimal number (range 0 through 53).

          Leading zeroes are permitted but not required.

     %OU
          Same as %U but using the locale's alternative numeric symbols.

     %V
          The ISO 8601 week number as a decimal number (range 1 through 53).

          Leading zeroes are permitted but not required.

          Note: Currently, this is not fully implemented.  The format is recognized, input is consumed but no field in TM is set.

     %w
          The day of the week as a decimal number (range 0 through 6), Sunday being 0.

          Leading zeroes are permitted but not required.

          Note: Currently, this is not fully implemented.  The format is recognized, input is consumed but no field in TM is set.

     %Ow
          Same as %w but using the locale's alternative numeric symbols.

     %W
          The week number of the current year as a decimal number (range 0 through 53).

          Leading zeroes are permitted but not required.

          Note: Currently, this is not fully implemented.  The format is recognized, input is consumed but no field in TM is set.

     %OW
          Same as %W but using the locale's alternative numeric symbols.

     %x
          The date using the locale's date format.

     %Ex
          Like %x but the locale's alternative data representation is used.

     %X
          The time using the locale's time format.

     %EX
          Like %X but the locale's alternative time representation is used.

     %y
          The year without a century as a decimal number (range 0 through 99).

          Leading zeroes are permitted but not required.

          Note that it is questionable to use this format without the %C format.  The strptime function does regard input values in the range 68 to 99 as the years 1969 to 1999 and the values 0 to 68 as the years 2000 to 2068.  But maybe this heuristic fails for some input data.

          Therefore it is best to avoid %y completely and use %Y instead.

     %Ey
          The offset from %EC in the locale's alternative representation.

     %Oy
          The offset of the year (from %C) using the locale's alternative numeric symbols.

     %Y
          The year as a decimal number, using the Gregorian calendar.

     %EY
          The full alternative year representation.

     %z
          The offset from UTC in ISO 8601/RFC 5322 format.

     %Z
          The time zone abbreviation.

          Note: Currently, this is not fully implemented.  The format is recognized, input is consumed but no field in TM is set.

     %%
          A literal % character.

     All other characters in the format string must have a matching character in the input string.  Exceptions are whitespace characters in the input string which can match zero or more whitespace characters in the format string.

     Portability Note: The XPG standard advises applications to use at least one whitespace character (as specified by isspace) or other non-alphanumeric characters between any two conversion specifications.  Theglibc does not have this limitation but other libraries might have trouble parsing formats like "%d%m%Y%H%M%S".

     The strptime function processes the input string from right to left.  Each of the three possible input elements (whitespace, literal, or format) are handled one after the other.  If the input cannot be matched to the format string the function stops.  The remainder of the format and input strings are not processed.

     The function returns a pointer to the first character it was unable to process.  If the input string contains more characters than required by the format string the return value points right after the last consumed input character.  If the whole input string is consumed the return value points to the NULL byte at the end of the string.  If an error occurs, i.e., strptime fails to match all of the format string, the function returns NULL.

The specification of the function in the XPG standard is rather vague, leaving out a few important pieces of information.  Most importantly, it does not specify what happens to those elements of TM which are not directly initialized by the different formats.  The implementations on different Unix systems vary here.

The glibcadj implementation does not touch those fields which are not directly initialized.  Exceptions are the tm_wday and tm_yday elements, which are recomputed if any of the year, month, or date elements changed.  This has two implications:

  * Before calling the strptime function for a new input string, you should prepare the TM structure you pass.  Normally this will mean initializing all values to zero.  Alternatively, you can set all fields to values like INT_MAX, allowing you to determine which elements were set by the function call.  Zero does not work here since it is a valid value for many of the fields.

     Careful initialization is necessary if you want to find out whether a certain field in TM was initialized by the function call.

  * You can construct a struct tm value with several consecutive strptime calls.  A useful application of this is e.g. the parsing of two separate strings, one containing date information and the other time information.  By parsing one after the other without clearing the structure in-between, you can construct a complete broken-down time.

The following example shows a function which parses a string which contains the date information in either US style or ISO 8601 form:

     const char *
     parse_date (const char *input, struct tm *tm)
     {
       const char *cp;

       /* First clear the result structure.  */
       memset (tm, '\0', sizeof (*tm));

       /* Try the ISO format first.  */
       cp = strptime (input, "%F", tm);
       if (cp == NULL)
         {
           /* Does not match.  Try the US form.  */
           cp = strptime (input, "%D", tm);
         }

       return cp;
     }

A More User-friendly Way to Parse Times and Dates
.................................................

The Unix standard defines another function for parsing date strings. The interface is weird, but if the function happens to suit your application it is just fine.  It is problematic to use this function in multi-threaded programs or libraries, since it returns a pointer to a static variable, and uses a global variable and global state based on an environment variable.

 -- Variable: getdate_err
     Unix98, time.h This variable of type int contains the error code of the last unsuccessful call to getdate.  Defined values are:

     1
          The environment variable DATEMSK is not defined or null.

     2
          The template file denoted by the DATEMSK environment variable cannot be opened.

     3
          Information about the template file cannot retrieved.

     4
          The template file is not a regular file.

     5
          An I/O error occurred while reading the template file.

     6
          Not enough memory available to execute the function.

     7
          The template file contains no matching template.

     8
          The input date is invalid, but would match a template otherwise.  This includes dates like February 31st, and dates which cannot be represented in a time_t variable.

 -- Function: struct tm * getdate (const char *STRING)
     Unix98, time.h prelim:getdate mtsenv mtslocale The interface to getdate is the simplest possible for a function to parse a string and return the value.  STRING is the input string and the result is returned in a statically-allocated variable.

     The details about how the string is processed are hidden from the user. In fact, they can be outside the control of the program.  Which formats are recognized is controlled by the file named by the environment variable DATEMSK.  This file should contain lines of valid format strings which could be passed to strptime.

     The getdate function reads these format strings one after the other and tries to match the input string.  The first line which completely matches the input string is used.

     Elements not initialized through the format string retain the values present at the time of the getdate function call.

     The formats recognized by getdate are the same as for strptime.  See above for an explanation.  There are only a few extensions to the strptime behavior:

       * If the %Z format is given the broken-down time is based on the current time of the time zone matched, not of the current time zone of the runtime environment.

          Note: This is not implemented (currently).  The problem is that time zone abbreviations are not unique.  If a fixed time zone is assumed for a given string (say EST meaning US East Coast time), then uses for countries other than the USA will fail.  So far we have found no good solution to this.

       * If only the weekday is specified the selected day depends on the current date.  If the current weekday is greater than or equal to the tm_wday value the current week's day is chosen, otherwise the day next week is chosen.

       * A similar heuristic is used when only the month is given and not the year.  If the month is greater than or equal to the current month, then the current year is used.  Otherwise it wraps to next year.  The first day of the month is assumed if one is not explicitly specified.

       * The current hour, minute, and second are used if the appropriate value is not set through the format.

       * If no date is given tomorrow's date is used if the time is smaller than the current time.  Otherwise today's date is taken.

     It should be noted that the format in the template file need not only contain format elements.  The following is a list of possible format strings (taken from the Unix standard):

          %m
          %A %B %d, %Y %H:%M:%S
          %A
          %B
          %m/%d/%y %I %p
          %d,%m,%Y %H:%M
          at %A the %dst of %B in %Y
          run job at %I %p,%B %dnd
          %A den %d. %B %Y %H.%M Uhr

     As you can see, the template list can contain very specific strings like run job at %I %p,%B %dnd.  Using the above list of templates and assuming the current time is Mon Sep 22 12:19:47 EDT 1986, we can obtain the following results for the given input.

     Input       Match   Result
     Mon         %a      Mon Sep 22 12:19:47 EDT 1986
     Sun         %a      Sun Sep 28 12:19:47 EDT 1986
     Fri         %a      Fri Sep 26 12:19:47 EDT 1986
     September   %B      Mon Sep 1 12:19:47 EDT 1986
     January     %B      Thu Jan 1 12:19:47 EST 1987
     December    %B      Mon Dec 1 12:19:47 EST 1986
     Sep Mon     %b %a   Mon Sep 1 12:19:47 EDT 1986
     Jan Fri     %b %a   Fri Jan 2 12:19:47 EST 1987
     Dec Mon     %b %a   Mon Dec 1 12:19:47 EST 1986
     Jan Wed 1989    %b %a %Y   Wed Jan 4 12:19:47 EST 1989
     Fri 9       %a %H   Fri Sep 26 09:00:00 EDT 1986
     Feb 10:30   %b %H:%S   Sun Feb 1 10:00:30 EST 1987
     10:30       %H:%M   Tue Sep 23 10:30:00 EDT 1986
     13:30       %H:%M   Mon Sep 22 13:30:00 EDT 1986

     The return value of the function is a pointer to a static variable of type struct tm, or a null pointer if an error occurred.  The result is only valid until the next getdate call, making this function unusable in multi-threaded applications.

     The errno variable is not changed.  Error conditions are stored in the global variable getdate_err.  See the description above for a list of the possible error values.

     Warning: The getdate function should never be used in SUID-programs.  The reason is obvious: using the DATEMSK environment variable you can get the function to open any arbitrary file and chances are high that with some bogus input (such as a binary file) the program will crash.

 -- Function: int getdate_r (const char *STRING, struct tm *TP)
     GNU, time.h The getdate_r function is the reentrant counterpart of getdate.  It does not use the global variable getdate_err to signal an error, but instead returns an error code.  The same error codes as described in the getdate_err documentation above are used, with 0 meaning success.

     Moreover, getdate_r stores the broken-down time in the variable of type struct tm pointed to by the second argument, rather than in a static variable.

     This function is not defined in the Unix standard.  Nevertheless it is available on some other Unix systems as well.

     The warning against using getdate in SUID-programs applies to getdate_r as well.

Specifying the Time Zone with TZ
--------------------------------

In POSIX systems, a user can specify the time zone by means of the TZ environment variable.  For information about how to set environment variables, see Environment Variables.  The functions for accessing the time zone are declared in time.h.

You should not normally need to set TZ.  If the system is configured properly, the default time zone will be correct.  You might set TZ if you are using a computer over a network from a different time zone, and would like times reported to you in the time zone local to you, rather than what is local to the computer.

The value of TZ can be in one of the following formats:

  * The geographical format specifies a location that stands for the past and future time zones observed in that location. See Geographical TZ. Here are some examples:

          Asia/Tokyo
          America/New_York
          /usr/share/zoneinfo/America/Nuuk

  * The proleptic format represents a time zone that has always been and always will be the same offset from UTC, optionally with a simple daylight saving scheme that has always been (and always will be) used every year. See Proleptic TZ. Here are some examples:

          JST-9
          EST+5EDT,M3.2.0/2,M11.1.0/2
          <-02>+2<-01>,M3.5.0/-1,M10.5.0/0

  * The colon format begins with :.  Here is an example.

          :/etc/localtime

     Each operating system can interpret this format differently; in theglibc, the : is ignored and CHARACTERS are treated as if they specified the geographical or proleptic format.

  * As an extension to POSIX, when the value of TZ is the empty string, theglibc uses UTC.

If the TZ environment variable does not have a value, the implementation chooses a time zone by default.  In theglibc, the default time zone is like the specification TZ=/etc/localtime (or TZ=/usr/local/etc/localtime, depending on how theglibc was configured; see Installation).  Other C libraries use their own rule for choosing the default time zone, so there is little we can say about them.

Geographical Format for TZ
..........................

The geographical format names a time zone ruleset maintained by the Time Zone Database (http://www.iana.org/time-zones) of time zone and daylight saving time information for most regions of the world. This public-domain database is maintained by a community of volunteers.

If the format's CHARACTERS begin with / it is an absolute file name; otherwise the library looks for the file /usr/share/zoneinfo/CHARACTERS.  The zoneinfo directory contains data files describing time zone rulesets in many different parts of the world.  The names represent major cities, with subdirectories for geographical areas; for example, America/New_York, Europe/London, Asia/Tokyo. These data files are installed by the system administrator, who also sets /etc/localtime to point to the data file for the local time zone ruleset.

If the file corresponding to CHARACTERS cannot be read or has invalid data, and CHARACTERS are not in the proleptic format, then theglibc silently defaults to UTC.  However, applications should not depend on this, as TZ formats may be extended in the future.

Proleptic Format for TZ
.......................

Although the proleptic format is cumbersome and inaccurate for old timestamps, POSIX.1-2017 and earlier specified details only for the proleptic format, and you may need to use it on small systems that lack a time zone information database.

The proleptic format is:

     STDOFFSET[DST[OFFSET][,START[/TIME],END[/TIME]]]

The STD string specifies the time zone abbreviation, which must be at least three bytes long, and which can appear in unquoted or quoted form. The unquoted form can contain only ASCII alphabetic characters. The quoted form can also contain ASCII digits, +, and -; it is quoted by surrounding it by < and >, which are not part of the abbreviation.  There is no space character separating the time zone abbreviation from the OFFSET, so these restrictions are necessary to parse the specification correctly.

The OFFSET specifies the time value you must add to the local time to get a UTC value.  It has syntax like:

     [+|-]HH[:MM[:SS]]

This is positive if the local time zone is west of the Prime Meridian and negative if it is east; this is opposite from the usual convention that positive time zone offsets are east of the Prime Meridian. The hour HH must be between 0 and 24 and may be a single digit, and the minutes MM and seconds SS, if present, must be between 0 and 59.

For example, to specify time in Panama, which is Eastern Standard Time without any daylight saving time alternative:

     EST+5

When daylight saving time is used, the proleptic format is more complicated. The initial STD and OFFSET specify the standard time zone, as described above.  The DST string and OFFSET are the abbreviation and offset for the corresponding daylight saving time zone; if the OFFSET is omitted, it defaults to one hour ahead of standard time.

The remainder of the proleptic format, which starts with the first comma, describes when daylight saving time is in effect.  This remainder is optional and if omitted, theglibc defaults to the daylight saving rules that would be used if TZ had the value "posixrules". However, other POSIX implementations default to different daylight saving rules, so portable TZ settings should not omit the remainder.

In the remainder, the START field is when daylight saving time goes into effect and the END field is when the change is made back to standard time.  The following formats are recognized for these fields:

JN
     This specifies the Julian day, with N between 1 and 365. February 29 is never counted, even in leap years.

N
     This specifies the Julian day, with N between 0 and 365. February 29 is counted in leap years.

MM.W.D
     This specifies day D of week W of month M.  The day D must be between 0 (Sunday) and 6.  The week W must be between 1 and 5; week 1 is the first week in which day D occurs, and week 5 specifies the last D day in the month.  The month M should be between 1 and 12.

The TIME fields specify when, in the local time currently in effect, the change to the other time occurs.  They have the same format as OFFSET except the hours part can range from -167 through 167; for example, -22:30 stands for 01:30 the previous day and 25:30 stands for 01:30 the next day.  If omitted, TIME defaults to 02:00:00.

Here are example TZ values with daylight saving time rules.

EST+5EDT,M3.2.0/2,M11.1.0/2
     In North American Eastern Standard Time (EST) and Eastern Daylight Time (EDT), the normal offset from UTC is 5 hours; since this is west of the Prime Meridian, the sign is positive.  Summer time begins on March's second Sunday at 2:00am, and ends on November's first Sunday at 2:00am.

IST-2IDT,M3.4.4/26,M10.5.0
     Israel Standard Time (IST) and Israel Daylight Time (IDT) are 2 hours ahead of the prime meridian in winter, springing forward an hour on March's fourth Thursday at 26:00 (i.e., 02:00 on the first Friday on or after March 23), and falling back on October's last Sunday at 02:00.

IST-1GMT0,M10.5.0,M3.5.0/1
     Irish Standard Time (IST) is 1 hour behind the Prime Meridian in summer, falling forward to Greenwich Mean Time (GMT, the Prime Meridian's time), on October's last Sunday at 00:00 and springing back on March's last Sunday at 01:00.  This is an example of ``negative daylight saving''; here,  daylight saving time is one hour west of standard time instead of the more usual one hour east.

<-02>+2<-01>,M3.5.0/-1,M10.5.0/0
     Most of Greenland is 2 hours behind UTC in winter.  Clocks follow the European Union rules of springing forward by one hour on March's last Sunday at 01:00 UTC (-01:00 local time) and falling back on October's last Sunday at 01:00 UTC (00:00 local time). The numeric abbreviations -02 and -01 stand for standard and daylight saving time, respectively.

The schedule of daylight saving time in any particular jurisdiction has changed over the years.  To be strictly correct, the conversion of dates and times in the past should be based on the schedule that was in effect then.  However, the proleptic format does not let you specify how the schedule has changed from year to year.  The most you can do is specify one particular schedule---usually the present day schedule---and this is used to convert any date, no matter when.  For precise time zone specifications, it is best to use the geographical format. See Geographical TZ.

State Variables for Time Zones
------------------------------

For compatibility with POSIX, theglibc defines global state variables that depend on time zone rules specified by the TZ environment variable.  However, these state variables are obsolescent and are planned to be removed in a future version of POSIX, and programs generally should avoid them because they are not thread-safe and their values are specified only when TZ uses the proleptic format.  See TZ Variable. Programs should instead use the tm_gmtoff and tm_zone members of struct tm.  See Broken-down Time.

 -- Function: void tzset (void)
     POSIX.1, time.h The tzset function initializes the state variables from the value of the TZ environment variable. It is not usually necessary for your program to call this function, partly because your program should not use the state variables, and partly because this function is called automatically when you use the time conversion functions localtime, mktime, strftime, strftime_l, and wcsftime, or the deprecated function ctime. Behavior is undefined if one thread accesses any of these variables directly while another thread is calling tzset or any other function that is required or allowed to behave as if it called tzset.

 -- Variable: char * tzname [2]
     POSIX.1, time.h The array tzname contains two strings, which are abbreviations of time zones (standard and Daylight Saving) that the user has selected.  tzname[0] abbreviates a standard time zone (for example, "EST"), and tzname[1] abbreviates a time zone when daylight saving time is in use (for example, "EDT").  These correspond to the STD and DST strings (respectively) when the TZ environment variable uses the proleptic format. The string values are unspecified if TZ uses the geographical format, so it is generally better to use the broken-down time structure's tm_zone member instead.

     In theglibc, the strings have a storage lifetime that lasts indefinitely; on some other platforms, the lifetime lasts only until TZ is changed.

     The tzname array is initialized by tzset. Though the strings are declared as char * the user must refrain from modifying them. Modifying the strings will almost certainly lead to trouble.

 -- Variable: long int timezone
     POSIX.1, time.h This contains the difference between UTC and local standard time, in seconds west of the Prime Meridian. For example, in the U.S. Eastern time zone, the value is 5*60*60.  Unlike the tm_gmtoff member of the broken-down time structure, this value is not adjusted for daylight saving, and its sign is reversed. The value is unspecified if TZ uses the geographical format, so it is generally better to use the broken-down time structure's tm_gmtoff member instead.

 -- Variable: int daylight
     POSIX.1, time.h

     This variable is nonzero if daylight saving time rules apply. A nonzero value does not necessarily mean that daylight saving time is now in effect; it means only that daylight saving time is sometimes in effect. This variable has little or no practical use; it is present for POSIX compatibility.

Time Functions Example
----------------------

Here is an example program showing the use of some of the calendar time functions.

          [file strftim.c.texi not included]

It produces output like this:

     2024-06-09 13:50:06
     Today is Sunday, June 09.
     The time is 01:50 PM.

Setting an Alarm
================

The alarm and setitimer functions provide a mechanism for a process to interrupt itself in the future.  They do this by setting a timer; when the timer expires, the process receives a signal.

Each process has three independent interval timers available:

  * A real-time timer that counts elapsed time.  This timer sends a SIGALRM signal to the process when it expires.

  * A virtual timer that counts processor time used by the process.  This timer sends a SIGVTALRM signal to the process when it expires.

  * A profiling timer that counts both processor time used by the process, and processor time spent in system calls on behalf of the process.  This timer sends a SIGPROF signal to the process when it expires.

     This timer is useful for profiling in interpreters.  The interval timer mechanism does not have the fine granularity necessary for profiling native code.

You can only have one timer of each kind set at any given time.  If you set a timer that has not yet expired, that timer is simply reset to the new value.

You should establish a handler for the appropriate alarm signal using signal or sigaction before issuing a call to setitimer or alarm.  Otherwise, an unusual chain of events could cause the timer to expire before your program establishes the handler.  In this case it would be terminated, since termination is the default action for the alarm signals.  See Signal Handling.

To be able to use the alarm function to interrupt a system call which might block otherwise indefinitely it is important to not set the SA_RESTART flag when registering the signal handler using sigaction.  When not using sigaction things get even uglier: the signal function has fixed semantics with respect to restarts.  The BSD semantics for this function is to set the flag. Therefore, if sigaction for whatever reason cannot be used, it is necessary to use sysv_signal and not signal.

The setitimer function is the primary means for setting an alarm. This facility is declared in the header file sys/time.h.  The alarm function, declared in unistd.h, provides a somewhat simpler interface for setting the real-time timer.

 -- Data Type: struct itimerval
     BSD, sys/time.h This structure is used to specify when a timer should expire.  It contains the following members:

     struct timeval it_interval
          This is the period between successive timer interrupts.  If zero, the alarm will only be sent once.

     struct timeval it_value
          This is the period between now and the first timer interrupt.  If zero, the alarm is disabled.

     The struct timeval data type is described in Time Types.

 -- Function: int setitimer (int WHICH, const struct itimerval *NEW, struct itimerval *OLD)
     BSD, sys/time.h The setitimer function sets the timer specified by WHICH according to NEW.  The WHICH argument can have a value of ITIMER_REAL, ITIMER_VIRTUAL, or ITIMER_PROF.

     If OLD is not a null pointer, setitimer returns information about any previous unexpired timer of the same kind in the structure it points to.

     The return value is 0 on success and -1 on failure.  The following errno error conditions are defined for this function:

     EINVAL
          The timer period is too large.

 -- Function: int getitimer (int WHICH, struct itimerval *OLD)
     BSD, sys/time.h The getitimer function stores information about the timer specified by WHICH in the structure pointed at by OLD.

     The return value and error conditions are the same as for setitimer.

ITIMER_REAL
     BSD, sys/time.h This constant can be used as the WHICH argument to the setitimer and getitimer functions to specify the real-time timer.

ITIMER_VIRTUAL
     BSD, sys/time.h This constant can be used as the WHICH argument to the setitimer and getitimer functions to specify the virtual timer.

ITIMER_PROF
     BSD, sys/time.h This constant can be used as the WHICH argument to the setitimer and getitimer functions to specify the profiling timer.

 -- Function: unsigned int alarm (unsigned int SECONDS)
     POSIX.1, unistd.h The alarm function sets the real-time timer to expire in SECONDS seconds.  If you want to cancel any existing alarm, you can do this by calling alarm with a SECONDS argument of zero.

     The return value indicates how many seconds remain before the previous alarm would have been sent.  If there was no previous alarm, alarm returns zero.

The alarm function could be defined in terms of setitimer like this:

     unsigned int
     alarm (unsigned int seconds)
     {
       struct itimerval old, new;
       new.it_interval.tv_usec = 0;
       new.it_interval.tv_sec = 0;
       new.it_value.tv_usec = 0;
       new.it_value.tv_sec = (long int) seconds;
       if (setitimer (ITIMER_REAL, &new, &old) < 0)
         return 0;
       else
         return old.it_value.tv_sec;
     }

There is an example showing the use of the alarm function in Handler Returns.

If you simply want your process to wait for a given number of seconds, you should use the sleep function.  See Sleeping.

You shouldn't count on the signal arriving precisely when the timer expires.  In a multiprocessing environment there is typically some amount of delay involved.

Portability Note: The setitimer and getitimer functions are derived from BSD Unix, while the alarm function is specified by POSIX.  setitimer is more powerful than alarm, but alarm is more widely used.

Sleeping
========

The function sleep gives a simple way to make the program wait for a short interval.  If your program doesn't use signals (except to terminate), then you can expect sleep to wait reliably throughout the specified interval.  Otherwise, sleep can return sooner if a signal arrives; if you want to wait for a given interval regardless of signals, use select (see Waiting for I/O) and don't specify any descriptors to wait for.

 -- Function: unsigned int sleep (unsigned int SECONDS)
     POSIX.1, unistd.h prelim:SIGCHLD/linux asunsafe acunsafe The sleep function waits for SECONDS seconds or until a signal is delivered, whichever happens first.

     If sleep returns because the requested interval is over, it returns a value of zero.  If it returns because of delivery of a signal, its return value is the remaining time in the sleep interval.

     The sleep function is declared in unistd.h.

Resist the temptation to implement a sleep for a fixed amount of time by using the return value of sleep, when nonzero, to call sleep again.  This will work with a certain amount of accuracy as long as signals arrive infrequently.  But each signal can cause the eventual wakeup time to be off by an additional second or so.  Suppose a few signals happen to arrive in rapid succession by bad luck---there is no limit on how much this could shorten or lengthen the wait.

Instead, compute the calendar time at which the program should stop waiting, and keep trying to wait until that calendar time.  This won't be off by more than a second.  With just a little more work, you can use select and make the waiting period quite accurate.  (Of course, heavy system load can cause additional unavoidable delays---unless the machine is dedicated to one application, there is no way you can avoid this.)

On some systems, sleep can do strange things if your program uses SIGALRM explicitly.  Even if SIGALRM signals are being ignored or blocked when sleep is called, sleep might return prematurely on delivery of a SIGALRM signal.  If you have established a handler for SIGALRM signals and a SIGALRM signal is delivered while the process is sleeping, the action taken might be just to cause sleep to return instead of invoking your handler.  And, if sleep is interrupted by delivery of a signal whose handler requests an alarm or alters the handling of SIGALRM, this handler and sleep will interfere.

On gnusystems, it is safe to use sleep and SIGALRM in the same program, because sleep does not work by means of SIGALRM.

 -- Function: int nanosleep (const struct timespec *REQUESTED_TIME, struct timespec *REMAINING_TIME)
     POSIX.1, time.h If resolution to seconds is not enough, the nanosleep function can be used.  As the name suggests the sleep interval can be specified in nanoseconds.  The actual elapsed time of the sleep interval might be longer since the system rounds the elapsed time you request up to the next integer multiple of the actual resolution the system can deliver.

     *REQUESTED_TIME is the elapsed time of the interval you want to sleep.

     If REMAINING_TIME is not the null pointer, the function returns as *REMAINING_TIME the elapsed time left in the interval for which you requested to sleep.  If the interval completed without getting interrupted by a signal, this is zero.

     struct timespec is described in Time Types.

     If the function returns because the interval is over, it returns zero. Otherwise it returns -1 and sets the global variable errno to one of the following values:

     EINTR
          The call was interrupted because a signal was delivered to the thread. If the REMAINING_TIME parameter is not the null pointer, the structure pointed to by REMAINING_TIME is updated to contain the remaining elapsed time.

     EINVAL
          The nanosecond value in the REQUESTED_TIME parameter contains an invalid value.  Either the value is negative or greater than or equal to 1000 million.

     This function is a cancellation point in multi-threaded programs.  This is a problem if the thread allocates some resources (like memory, file descriptors, semaphores or whatever) at the time nanosleep is called.  If the thread gets canceled, these resources stay allocated until the program ends.  To avoid this, calls to nanosleep should be protected using cancellation handlers.

     The nanosleep function is declared in time.h.

 -- Function: int clock_nanosleep (clockid_t CLOCK, int FLAGS, const struct timespec *REQUESTED_TIME, struct timespec *REMAINING_TIME)
     POSIX.1-2001, time.h This function is similar to nanosleep while additionally providing the caller with a way to specify the clock to be used to measure elapsed time and express the sleep interval in absolute or relative terms.  It returns zero when returning because the interval is over, and a positive error number corresponding to the error encountered otherwise.  This is different from nanosleep, which returns -1 upon failure and sets the global variable errno according to the error encountered instead.

     Except for the return value convention and the way to communicate an error condition the call:

          nanosleep (REQUESTED_TIME, REMAINING_TIME)

     is analogous to:

          clock_nanosleep (CLOCK_REALTIME, 0, REQUESTED_TIME, REMAINING_TIME)

     The CLOCK argument specifies the clock to use. See Getting the Time, for the clockid_t type and possible values of CLOCK.  Not all clocks listed are supported for use with clock_nanosleep.  For details, see the manual page clock_nanosleep,2.

     The FLAGS argument is either 0 or TIMER_ABSTIME.  If FLAGS is 0, then clock_nanosleep interprets REQUESTED_TIME as an interval relative to the current time specified by CLOCK.  If it is TIMER_ABSTIME instead, REQUESTED_TIME specifies an absolute time measured by CLOCK; if at the time of the call the value requested is less than or equal to the clock specified, then the function returns right away.  When FLAGS is TIMER_ABSTIME, REMAINING_TIME is not updated.

     The clock_nanosleep function returns error codes as positive return values.  The error conditions for clock_nanosleep are the same as for nanosleep, with the following conditions additionally defined:

     EINVAL
          The CLOCK argument is not a valid clock.

     EOPNOTSUPP
          The CLOCK argument is not supported by the kernel for clock_nanosleep.

     The clock_nanosleep function is declared in time.h.