This section describes facilities for keeping track of calendar time. the section called “Time Basics”.
The GNU C library represents calendar time three ways:
Simple time (the time_t data type) is a compact representation, typically giving the number of seconds of elapsed time since some implementation-specific base time.
There is also a "high-resolution time" representation. Like simple time, this represents a calendar time as an elapsed time since a base time, but instead of measuring in whole seconds, it uses a struct timeval data type, which includes fractions of a second. Use this time representation instead of simple time when you need greater precision.
Local time or broken-down time (the struct tm data type) represents a calendar time as a set of components specifying the year, month, and so on in the Gregorian calendar, for a specific time zone. This calendar time representation is usually used only to communicate with people.
This section describes the time_t data type for representing calendar time as simple time, and the functions which operate on simple time objects. These facilities are declared in the header file time.h. function>time_t/function> This is the data type used to represent simple time. Sometimes, it also represents an elapsed time. When interpreted as a calendar time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time. (This calendar time is sometimes referred to as the epoch.) POSIX requires that this count not include leap seconds, but on some systems this count includes leap seconds if you set TZ to certain values (the section called “Specifying the Time Zone with TZ”).
Note that a simple time has no concept of local time zone. Calendar Time T is the same instant in time regardless of where on the globe the computer is.
In the GNU C library, time_t is equivalent to long int. In other systems, time_t might be either an integer or floating-point type.
The function difftime tells you the elapsed time between two simple calendar times, which is not always as easy to compute as just subtracting. the section called “Elapsed Time”.
time_t function>time/function> (time_t *result) The time function returns the current calendar time as a value of type time_t. If the argument result is not a null pointer, the calendar time value is also stored in *result. If the current calendar time is not available, the value (time_t)(-1) is returned.
int function>stime/function> (time_t *newtime) stime sets the system clock, i.e. it tells the system that the current calendar time is newtime, where newtime is interpreted as described in the above definition of time_t.
settimeofday is a newer function which sets the system clock to better than one second precision. settimeofday is generally a better choice than stime. the section called “High-Resolution Calendar”.
Only the superuser can set the system clock.
If the function succeeds, the return value is zero. Otherwise, it is -1 and errno is set accordingly:
The process is not superuser.
The time_t data type used to represent simple times has a resolution of only one second. Some applications need more precision.
So, the GNU C library also contains functions which are capable of representing calendar times to a higher resolution than one second. The functions and the associated data types described in this section are declared in sys/time.h. function>struct timezone/function> The struct timezone structure is used to hold minimal information about the local time zone. It has the following members:
This is the number of minutes west of UTC.
If nonzero, Daylight Saving Time applies during some part of the year.
The struct timezone type is obsolete and should never be used. Instead, use the facilities described in the section called “Functions and Variables for Time Zones”.
int function>gettimeofday/function> (struct timeval *tp, struct timezone *tzp) The gettimeofday function returns the current calendar time as the elapsed time since the epoch in the struct timeval structure indicated by tp. (the section called “Elapsed Time” for a description of struct timespec). Information about the time zone is returned in the structure pointed at tzp. If the tzp argument is a null pointer, time zone information is ignored.
The return value is 0 on success and -1 on failure. The following errno error condition is defined for this function:
The operating system does not support getting time zone information, and tzp is not a null pointer. The GNU operating system does not support using struct timezone to represent time zone information; that is an obsolete feature of 4.3 BSD. Instead, use the facilities described in the section called “Functions and Variables for Time Zones”.
int function>settimeofday/function> (const struct timeval *tp, const struct timezone *tzp) The settimeofday function sets the current calendar time in the system clock according to the arguments. As for gettimeofday, the calendar time is represented as the elapsed time since the epoch. As for gettimeofday, time zone information is ignored if tzp is a null pointer.
You must be a privileged user in order to use settimeofday.
Some kernels automatically set the system clock from some source such as a hardware clock when they start up. Others, including Linux, place the system clock in an "invalid" state (in which attempts to read the clock fail). A call of stime removes the system clock from an invalid state, and system startup scripts typically run a program that calls stime.
settimeofday causes a sudden jump forwards or backwards, which can cause a variety of problems in a system. Use adjtime (below) to make a smooth transition from one time to another by temporarily speeding up or slowing down the clock.
With a Linux kernel, adjtimex does the same thing and can also make permanent changes to the speed of the system clock so it doesn't need to be corrected as often.
The return value is 0 on success and -1 on failure. The following errno error conditions are defined for this function:
This process cannot set the clock because it is not privileged.
The operating system does not support setting time zone information, and tzp is not a null pointer.
int function>adjtime/function> (const struct timeval *delta, struct timeval *olddelta) This function speeds up or slows down the system clock in order to make a gradual adjustment. This ensures that the calendar time reported by the system clock is always monotonically increasing, which might not happen if you simply set the clock.
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 speeded 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.
This function is typically used to synchronize the clocks of computers in a local network. You must be a privileged user to use it.
With a Linux kernel, you can use the adjtimex function to permanently change the clock speed.
The return value is 0 on success and -1 on failure. The following errno error condition is defined for this function:
You do not have privilege to set the time.
Portability Note: The gettimeofday, settimeofday, and adjtime functions are derived from BSD.
Symbols for the following function are declared in sys/timex.h.
int function>adjtimex/function> (struct timex *timex) adjtimex is functionally identical to ntp_adjtime. the section called “High Accuracy Clock”.
This function is present only with a Linux kernel.
Calendar time is represented by the usual GNU C library functions as an elapsed time since a fixed base calendar time. 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. Broken-down time values are not useful for calculations, but 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.
function>struct tm/function> 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.
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).
This is the number of full minutes since the top of the hour (in the range 0 through 59).
This is the number of full hours past midnight (in the range 0 through 23).
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.
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).
This is the number of full calendar years since 1900.
This is the number of full days since Sunday (in the range 0 through 6).
This is the number of full days since the beginning of the year (in the range 0 through 365).
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.
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 UTC. For example, for U.S. Eastern Standard Time, the value is -5*60*60. The tm_gmtoff field is derived from BSD and is a GNU library extension; it is not visible in a strict ISO C environment.
This field is the name for the time zone that was used to compute this broken-down time value. Like tm_gmtoff, this field is a BSD and GNU extension, and is not visible in a strict ISO C environment.
struct tm * function>localtime/function> (const time_t *time) 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 ctime, gmtime, or localtime. (But no other library function overwrites the contents of this object.)
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 has one other effect: it sets the variable tzname with information about the current time zone. the section called “Functions and Variables for Time Zones”.
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. POSIX.1c introduced a variant of this function.
struct tm * function>localtime_r/function> (const time_t *time, struct tm *resultp) 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.
If the conversion is successful the function returns a pointer to the object the result was written into, i.e., it returns resultp.
struct tm * function>gmtime/function> (const time_t *time) This function is similar to localtime, except that the broken-down time is expressed as Coordinated Universal Time (UTC) (formerly called Greenwich Mean Time (GMT)) rather than relative to a local time zone.
As for the localtime function we have the problem that the result is placed in a static variable. POSIX.1c also provides a replacement for gmtime.
struct tm * function>gmtime_r/function> (const time_t *time, struct tm *resultp) This function is similar to localtime_r, except that it converts just like gmtime the given time as Coordinated Universal Time.
If the conversion is successful the function returns a pointer to the object the result was written into, i.e., it returns resultp.
time_t function>mktime/function> (struct tm *brokentime) The mktime function is used to convert a broken-down time structure to a simple time representation. It also "normalizes" the contents of the broken-down time structure, by filling in the day of week and day of year based on the other date and time components.
The mktime function ignores the specified contents of the tm_wday and tm_yday 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 tm_wday and tm_yday).
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 variable tzname with information about the current time zone. the section called “Functions and Variables for Time Zones”.
time_t function>timelocal/function> (struct tm *brokentime) 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.
time_t function>timegm/function> (struct tm *brokentime) timegm is functionally identical to mktime except it always takes the input values to be Coordinated Universal Time (UTC) regardless of any local time zone setting.
Note that timegm is the inverse of gmtime.
Portability note:mktime is essentially universally available. timegm is rather rare. For the most portable conversion from a UTC broken-down time to a simple time, set the TZ environment variable to UTC, call mktime, then set TZ back.
The ntp_gettime and ntp_adjtime functions provide an interface to monitor and manipulate the system clock to maintain high accuracy time. For example, you can fine tune the speed of the clock or synchronize it with another time source.
A typical use of these functions is by a server implementing the Network Time Protocol to synchronize the clocks of multiple systems and high precision clocks.
These functions are declared in sys/timex.h.
function>struct ntptimeval/function> This structure is used for information about the system clock. It contains the following members:
This is the current calendar time, expressed as the elapsed time since the epoch. The struct timeval data type is described in the section called “Elapsed Time”.
This is the maximum error, measured in microseconds. Unless updated via ntp_adjtime periodically, this value will reach some platform-specific maximum value.
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.
int function>ntp_gettime/function> (struct ntptimeval *tptr) 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 a 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:
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.
function>struct timex/function> This structure is used to control and monitor the system clock. It contains the following members:
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_.
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.
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.
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.
This is the estimated error, measured in microseconds. This value can be set using bit MOD_ESTERROR.
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.
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.
This value represents the accuracy or the maximum error when reading the system clock. The value is expressed in microseconds.
This value represents the maximum frequency error of the system clock in scaled PPM. This value is used to increase the maxerror every second.
The current calendar time.
The elapsed time between clock ticks in microseconds. A clock tick is a periodic timer interrupt on which the system clock is based.
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.
This value expresses a median filtered average of the PPS signal's dispersion in microseconds.
This value is a binary exponent for the duration of the PPS calibration interval, ranging from PPS_SHIFT to PPS_SHIFTMAX.
This value represents the median filtered dispersion of the PPS frequency in scaled PPM.
This counter represents the number of pulses where the jitter exceeded the allowed maximum MAXTIME.
This counter reflects the number of successful calibration intervals.
This counter represents the number of calibration errors (caused by large offsets or jitter).
This counter denotes the number of of calibrations where the stability exceeded the threshold.
int function>ntp_adjtime/function> (struct timex *tptr) 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:
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.
The process specified a settings update, but is not superuser.
For more details see RFC1305 (Network Time Protocol, Version 3) and related documents.
Portability note: Early versions of the GNU C library did not have this function but did have the synonymous adjtimex.
The functions described in this section format calendar time values as strings. These functions are declared in the header file time.h. char * function>asctime/function> (const struct tm *brokentime) 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.
The return value points to a statically allocated string, which might be overwritten by subsequent calls to asctime or ctime. (But no other library function overwrites the contents of this string.)
char * function>asctime_r/function> (const struct tm *brokentime, char *buffer) 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.
If no error occurred the function returns a pointer to the string the result was written into, i.e., it returns buffer. Otherwise return NULL.
char * function>ctime/function> (const time_t *time) 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))
ctime sets the variable tzname, because localtime does so. the section called “Functions and Variables for Time Zones”.
char * function>ctime_r/function> (const time_t *time, char *buffer) This function is similar to ctime, but places the result in the string pointed to by buffer. It is equivalent to (written using gcc extensions, ):
({ struct tm tm; asctime_r (localtime_r (time, tm), buf); })
If no error occurred the function returns a pointer to the string the result was written into, i.e., it returns buffer. Otherwise return NULL.
size_t function>strftime/function> (char *s, size_t size, const char *template, const struct tm *brokentime) This function is similar to the sprintf function (the section called “Formatted Input ”), but the conversion specifications that can appear in the format template template are specialized for printing components of the date and time brokentime according to the locale currently specified for time conversion (Chapter 8).
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.
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 (the section called “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 is 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, which are POSIX.2 extensions, are:
Use the locale's alternate 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.
Use the locale's alternate numeric symbols for numbers. This modifier applies only to numeric format specifiers.
If the format supports the modifier but no alternate 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:
The abbreviated weekday name according to the current locale.
The full weekday name according to the current locale.
The abbreviated month name according to the current locale.
The full month name according to the current locale.
The preferred calendar time representation for the current locale.
The century of the year. This is equivalent to the greatest integer not greater than the year divided by 100.
This format is a POSIX.2 extension and also appears in ISO C99.
The day of the month as a decimal number (range 01 through 31).
The date using the format %m/%d/%y.
This format is a POSIX.2 extension and also appears in ISO C99.
The day of the month like with %d, but padded with blank (range 1 through 31).
This format is a POSIX.2 extension and also appears in ISO C99.
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.
This format is a ISO C99 extension.
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.
This format was introduced in ISO C99.
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.
This format was introduced in ISO C99 but was previously available as a GNU extension.
The abbreviated month name according to the current locale. The action is the same as for %b.
This format is a POSIX.2 extension and also appears in ISO C99.
The hour as a decimal number, using a 24-hour clock (range 00 through 23).
The hour as a decimal number, using a 12-hour clock (range 01 through 12).
The day of the year as a decimal number (range 001 through 366).
The hour as a decimal number, using a 24-hour clock like %H, but padded with blank (range 0 through 23).
This format is a GNU extension.
The hour as a decimal number, using a 12-hour clock like %I, but padded with blank (range 1 through 12).
This format is a GNU extension.
The month as a decimal number (range 01 through 12).
The minute as a decimal number (range 00 through 59).
A single \n (newline) character.
This format is a POSIX.2 extension and also appears in ISO C99.
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.
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.
This format was introduced in ISO C99 but was previously available as a GNU extension.
The complete calendar time using the AM/PM format of the current locale.
This format is a POSIX.2 extension and also appears in ISO C99.
The hour and minute in decimal numbers using the format %H:%M.
This format was introduced in ISO C99 but was previously available as a GNU extension.
The number of seconds since the 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.
The seconds as a decimal number (range 00 through 60).
A single \t (tabulator) character.
This format is a POSIX.2 extension and also appears in ISO C99.
The time of day using decimal numbers using the format %H:%M:%S.
This format is a POSIX.2 extension.
The day of the week as a decimal number (range 1 through 7), Monday being 1.
This format is a POSIX.2 extension and also appears in ISO C99.
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.
The ISO 8601:1988 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.
This format is a POSIX.2 extension and also appears in ISO C99.
The day of the week as a decimal number (range 0 through 6), Sunday being 0.
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.
The preferred date representation for the current locale.
The preferred time of day representation for the current locale.
The year without a century as a decimal number (range 00 through 99). This is equivalent to the year modulo 100.
The year as a decimal number, using the Gregorian calendar. Years before the year 1 are numbered 0, -1, and so on.
RFC 822/ISO 8601:1988 style numeric time zone (e.g., -0600 or +0100), or nothing if no time zone is determinable.
This format was introduced in ISO C99 but was previously available as a GNU extension.
A full RFC 822 timestamp is generated by the format "%a, %d %b %Y %H:%M:%S %z" (or the equivalent "%a, %d %b %Y %T %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.
According to POSIX.1 every call to strftime implies a call to tzset. So the contents of the environment variable TZ is examined before any output is produced.
For an example of strftime, see the section called “Time Functions Example”.
size_t function>wcsftime/function> (wchar_t *s, size_t size, const wchar_t *template, const struct tm *brokentime) 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 character, 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.
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.
he 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.
char * function>strptime/function> (const char *s, const char *fmt, struct tm *tp) 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 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:
The weekday name according to the current locale, in abbreviated form or the full name.
The month name according to the current locale, in abbreviated form or the full name.
The date and time representation for the current locale.
Like %c but the locale's alternative date and time format is used.
The century of the year.
It makes sense to use this format only if the format string also contains the %y format.
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.
The day of the month as a decimal number (range 1 through 31). Leading zeroes are permitted but not required.
Same as %d but using the locale's alternative numeric symbols.
Leading zeroes are permitted but not required.
Equivalent to %m/%d/%y.
Equivalent to %Y-%m-%d, which is the ISO 8601 date format.
This is a GNU extension following an ISO C99 extension to strftime.
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.
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.
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.
Same as %H but using the locale's alternative numeric symbols.
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.
Same as %I but using the locale's alternative numeric symbols.
The day of the year as a decimal number (range 1 through 366).
Leading zeroes are permitted but not required.
The month as a decimal number (range 1 through 12).
Leading zeroes are permitted but not required.
Same as %m but using the locale's alternative numeric symbols.
The minute as a decimal number (range 0 through 59).
Leading zeroes are permitted but not required.
Same as %M but using the locale's alternative numeric symbols.
Matches any white space.
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.
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.
The hour and minute in decimal numbers using the format %H:%M.
%R is a GNU extension following a GNU extension to strftime.
The number of seconds since the 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.
The seconds as a decimal number (range 0 through 60).
Leading zeroes are permitted but not required.
Note: 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.
Same as %S but using the locale's alternative numeric symbols.
Equivalent to the use of %H:%M:%S in this place.
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.
The week number of the current year as a decimal number (range 0 through 53).
Leading zeroes are permitted but not required.
Same as %U but using the locale's alternative numeric symbols.
The ISO 8601:1988 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.
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.
Same as %w but using the locale's alternative numeric symbols.
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.
Same as %W but using the locale's alternative numeric symbols.
The date using the locale's date format.
Like %x but the locale's alternative data representation is used.
The time using the locale's time format.
Like %X but the locale's alternative time representation is used.
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.
The offset from %EC in the locale's alternative representation.
The offset of the year (from %C) using the locale's alternative numeric symbols.
The year as a decimal number, using the Gregorian calendar.
The full alternative year representation.
Equivalent to the use of %a, %d %b %Y %H:%M:%S %z in this place. This is the full ISO 8601 date and time format.
The timezone name.
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 white spaces in the input string which can match zero or more white space characters in the format string.
The strptime function processes the input string from right to left. Each of the three possible input elements (white space, 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 GNU libc 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 are 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 is 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; }
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 (an environment variable).
function>getdate_err/function> This variable of type int contains the error code of the last unsuccessful call to getdate. Defined values are:
The environment variable DATEMSK is not defined or null.
The template file denoted by the DATEMSK environment variable cannot be opened.
Information about the template file cannot retrieved.
The template file is not a regular file.
An I/O error occurred while reading the template file.
Not enough memory available to execute the function.
The template file contains no matching template.
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.
struct tm * function>getdate/function> (const char *string) 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 timezone matched, not of the current timezone of the runtime environment.
Note: This is not implemented (currently). The problem is that timezone names are not unique. If a fixed timezone 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 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.
int function>getdate_r/function> (const char *string, struct tm *tp) 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.
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 the section called “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.
In POSIX.1 systems the value of the TZ variable can be in one of three formats. With the GNU C library, the most common format is the last one, which can specify a selection from a large database of time zone information for many regions of the world. The first two formats are used to describe the time zone information directly, which is both more cumbersome and less precise. But the POSIX.1 standard only specifies the details of the first two formats, so it is good to be familiar with them in case you come across a POSIX.1 system that doesn't support a time zone information database.
The first format is used when there is no Daylight Saving Time (or summer time) in the local time zone:
stdoffset
The std string specifies the name of the time zone. It must be three or more characters long and must not contain a leading colon, embedded digits, commas, nor plus and minus signs. There is no space character separating the time zone name 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 Coordinated Universal Time 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. The hour must be between 0 and 23, and the minute and seconds between 0 and 59.
For example, here is how we would specify Eastern Standard Time, but without any Daylight Saving Time alternative:
EST+5
The second format is used when there is Daylight Saving Time:
stdoffsetdst [offset],start[/time],end[/time]
The initial std and offset specify the standard time zone, as described above. The dst string and offset specify the name 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 specification describes when Daylight Saving Time is in effect. 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:
This specifies the Julian day, with n between 1 and 365. February 29 is never counted, even in leap years.
This specifies the Julian day, with n between 0 and 365. February 29 is counted in leap years.
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 lastd 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. If omitted, the default is 02:00:00.
For example, here is how you would specify the Eastern time zone in the United States, including the appropriate Daylight Saving Time and its dates of applicability. The normal offset from UTC is 5 hours; since this is west of the prime meridian, the sign is positive. Summer time begins on the first Sunday in April at 2:00am, and ends on the last Sunday in October at 2:00am.
EST+5EDT,M4.1.0/2,M10.5.0/2
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, this format has no facilities to 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 time zone information database (see below).
The third format looks like this:
:characters
Each operating system interprets this format differently; in the GNU C library, characters is the name of a file which describes the time zone.
If the TZ environment variable does not have a value, the operation chooses a time zone by default. In the GNU C library, the default time zone is like the specification TZ=:/etc/localtime (or TZ=:/usr/local/etc/localtime, depending on how GNU C library was configured; Appendix C). Other C libraries use their own rule for choosing the default time zone, so there is little we can say about them.
If characters begins with a slash, it is an absolute file name; otherwise the library looks for the file /share/lib/zoneinfo/characters. The zoneinfo directory contains data files describing local time zones 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/Hong_Kong. 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. The GNU C library comes with a large database of time zone information for most regions of the world, which is maintained by a community of volunteers and put in the public domain.
char * function>tzname/function> [2] The array tzname contains two strings, which are the standard names of the pair of time zones (standard and Daylight Saving) that the user has selected. tzname[0] is the name of the standard time zone (for example, "EST"), and tzname[1] is the name for the time zone when Daylight Saving Time is in use (for example, "EDT"). These correspond to the std and dst strings (respectively) from the TZ environment variable. If Daylight Saving Time is never used, tzname[1] is the empty string.
The tzname array is initialized from the TZ environment variable whenever tzset, ctime, strftime, mktime, or localtime is called. If multiple abbreviations have been used (e.g. "EWT" and "EDT" for U.S. Eastern War Time and Eastern Daylight Time), the array contains the most recent abbreviation.
The tzname array is required for POSIX.1 compatibility, but in GNU programs it is better to use the tm_zone member of the broken-down time structure, since tm_zone reports the correct abbreviation even when it is not the latest one.
Though the strings are declared as char * the user must refrain from modifying these strings. Modifying the strings will almost certainly lead to trouble.
void function>tzset/function> (void) The tzset function initializes the tzname variable from the value of the TZ environment variable. It is not usually necessary for your program to call this function, because it is called automatically when you use the other time conversion functions that depend on the time zone.
The following variables are defined for compatibility with System V Unix. Like tzname, these variables are set by calling tzset or the other time conversion functions.
long int function>timezone/function> This contains the difference between UTC and the latest local standard time, in seconds west of UTC. 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. In GNU programs it is better to use tm_gmtoff, since it contains the correct offset even when it is not the latest one.
int function>daylight/function> This variable has a nonzero value 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.
Here is an example program showing the use of some of the calendar time functions.
#include time.h #include stdio.h #define SIZE 256 int main (void) { char buffer[SIZE]; time_t curtime; struct tm *loctime; /* Get the current time. */ curtime = time (NULL); /* Convert it to local time representation. */ loctime = localtime (curtime); /* Print out the date and time in the standard format. */ fputs (asctime (loctime), stdout); /* Print it out in a nice format. */ strftime (buffer, SIZE, "Today is %A, %B %d.\n", loctime); fputs (buffer, stdout); strftime (buffer, SIZE, "The time is %I:%M %p.\n", loctime); fputs (buffer, stdout); return 0; }
It produces output like this:
Wed Jul 31 13:02:36 1991 Today is Wednesday, July 31. The time is 01:02 PM.