Go to the first, previous, next, last section, table of contents.
This chapter describes functions for manipulating dates and times, including functions for determining what the current time is and conversion between different time representations.
The time functions fall into three main categories:
If you're trying to optimize your program or measure its efficiency, it's
very useful to be able to know how much processor time or CPU
time it has used at any given point. Processor time is different from
actual wall clock time because it doesn't include any time spent waiting
for I/O or when some other process is running. Processor time is
represented by the data type clock_t, and is given as a number of
clock ticks relative to an arbitrary base time marking the beginning
of a single program invocation.
To get the elapsed CPU time used by a process, 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), like this:
#include <time.h> clock_t start, end; double elapsed; start = clock(); ... /* Do the work. */ end = clock(); elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
Different computers and operating systems vary wildly in how they keep track of processor time. It's common for the internal processor clock to have a resolution somewhere between hundredths and millionths of a second.
In the GNU system, clock_t is equivalent to long int and
CLOCKS_PER_SEC is an integer value. But in other systems, both
clock_t and the type of the macro CLOCKS_PER_SEC can be
either integer or floating-point types. Casting processor time values
to double, as in the example above, makes sure that operations
such as arithmetic and printing work properly and consistently no matter
what the underlying representation is.
clock function.
CLOCKS_PER_SEC.
clock function.
Values of type clock_t are in units of clock ticks.
clock returns the
value (clock_t)(-1).
The times function returns more detailed information about
elapsed processor time in a struct tms object. You should
include the header file `sys/times.h' to use this facility.
tms structure is used to return information about process
times. It contains at least the following members:
clock_t tms_utime
clock_t tms_stime
clock_t tms_cutime
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 section Process Completion. In other words, it
represents the total CPU 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
tms_cutime, but represents the total CPU time
used by the system on behalf of all the terminated child processes of the
calling process.
All of the times are given in clock ticks. These are absolute values; in a newly created process, they are all zero. See section Creating a Process.
times function stores the processor time information for
the calling process in buffer.
The return value is the same as the value of clock(): the elapsed
real time relative to an arbitrary base. The base is a constant within a
particular process, and typically represents the time since system
start-up. A value of (clock_t)(-1) is returned to indicate failure.
Portability Note: The clock function described in
section Basic CPU Time Inquiry, is specified by the ISO C standard. The
times function is a feature of POSIX.1. In the GNU system, the
value returned by the clock function is equivalent to the sum of
the tms_utime and tms_stime fields returned by
times.
This section describes facilities for keeping track of dates and times according to the Gregorian calendar.
There are three representations for date and time information:
time_t data type) is a compact
representation, typically giving the number of seconds elapsed since
some implementation-specific base time.
struct
timeval data type) that includes fractions of a second. Use this time
representation instead of ordinary calendar time when you need greater
precision.
struct
tm data type) represents the date and time as a set of components
specifying the year, month, and so on, for a specific time zone.
This time representation is usually used in conjunction with formatting
date and time values.
This section describes the time_t data type for representing
calendar time, and the functions which operate on calendar time objects.
These facilities are declared in the header file `time.h'.
TZ to certain values (see section Specifying the Time Zone with TZ).
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.
difftime function returns the number of seconds elapsed
between time time1 and time time0, as a value of type
double. The difference ignores leap seconds unless leap
second support is enabled.
In the GNU system, you can simply subtract time_t values. But on
other systems, the time_t data type might use some other encoding
where subtraction doesn't work directly.
time function returns the current time as a value of type
time_t. If the argument result is not a null pointer, the
time value is also stored in *result. If the calendar
time is not available, the value (time_t)(-1) is returned.
The time_t data type used to represent calendar 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'.
struct timeval structure represents a calendar time. It
has the following members:
long int tv_sec
time_t value.
long int tv_usec
tv_sec member is the number of seconds in the interval, and
tv_usec is the number of additional microseconds.
struct timezone structure is used to hold minimal information
about the local time zone. It has the following members:
int tz_minuteswest
int tz_dsttime
The struct timezone type is obsolete and should never be used.
Instead, use the facilities described in section Functions and Variables for Time Zones.
It is often necessary to subtract two values of type struct
timeval. Here is the best way to do this. It works even on some
peculiar operating systems where the tv_sec member has an
unsigned type.
/* Subtract the `struct timeval' values X and Y,
storing the result in RESULT.
Return 1 if the difference is negative, otherwise 0. */
int
timeval_subtract (result, x, y)
struct timeval *result, *x, *y;
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
gettimeofday function returns the current date and time in the
struct timeval structure indicated by tp. 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:
ENOSYS
struct timezone to represent time zone
information; that is an obsolete feature of 4.3 BSD.
Instead, use the facilities described in section Functions and Variables for Time Zones.
settimeofday function sets the current date and time
according to the arguments. 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.
The return value is 0 on success and -1 on failure. The
following errno error conditions are defined for this function:
EPERM
ENOSYS
The delta argument specifies a relative adjustment to be made to the current time. If negative, the system clock is slowed down for a while until it has lost this much 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.
The return value is 0 on success and -1 on failure. The
following errno error condition is defined for this function:
EPERM
Portability Note: The gettimeofday, settimeofday,
and adjtime functions are derived from BSD.
Calendar time is represented as a number of seconds. This is convenient for calculation, but has no resemblance to the way people normally represent dates and times. By contrast, broken-down time is a binary representation 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.
A broken-down time value is always relative to a choice of local time zone, and it also indicates which time zone was used.
The symbols in this section are declared in the header file `time.h'.
int tm_sec
0 through 59. (The actual upper limit is 60, to allow
for leap seconds if leap second support is available.)
int tm_min
0 through
59.
int tm_hour
0 through
23.
int tm_mday
1 through 31.
int tm_mon
0 through
11.
int tm_year
1900.
int tm_wday
0 through
6.
int tm_yday
0 through
365.
int tm_isdst
long int tm_gmtoff
-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.
const char *tm_zone
tm_gmtoff, this field is a BSD and
GNU extension, and is not visible in a strict ISO C environment.
localtime function converts the calendar 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. See section 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 varient of this function.
localtime_r function works just like the localtime
function. It takes a pointer to a variable containing the calendar 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.
localtime, except that the broken-down
time is expressed as Coordinated Universal Time (UTC)---that is, as
Greenwich Mean Time (GMT)---rather than relative to the local time zone.
Recall that calendar times are always expressed in coordinated universal time.
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.
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.
mktime function is used to convert a broken-down time structure
to a calendar 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 compute the
calendar time; it's permissible for these components to have
unnormalized values outside of 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 calendar 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. See section Functions and Variables for Time Zones.
The functions described in this section format time values as strings. These functions are declared in the header file `time.h'.
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.)
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 at least room
for 16 bytes.
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.
ctime function is similar to asctime, except that the
time value is specified as a time_t calendar 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. See section Functions and Variables for Time Zones.
ctime, only that it places the result
in the string pointed to by buffer. It is equivalent to (written
using gcc extensions, see section `Statement Exprs' in Porting and Using gcc):
({ 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.
sprintf function (see section 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 (see section Locales and Internationalization).
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:
_
-
0
^
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:
E
%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
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:
%a
%A
%b
%B
%c
%C
%d
01 through 31).
%D
%m/%d/%y.
This format is a POSIX.2 extension.
%e
%d, but padded with blank (range
1 through 31).
This format is a POSIX.2 extension.
%f
1 through
7), Monday being 1.
This format is a ISO C 9X extension.
%F
%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 C 9X extension.
%g
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 is a GNU extension.
%G
%Y, except that if the ISO week number (see
%V) belongs to the previous or next year, that year is used
instead.
This format is a GNU extension.
%h
%b.
This format is a POSIX.2 extension.
%H
00 through
23).
%I
01 through
12).
%j
001 through 366).
%k
%H, but
padded with blank (range 0 through 23).
This format is a GNU extension.
%l
%I, but
padded with blank (range 1 through 12).
This format is a GNU extension.
%m
01 through 12).
%M
00 through 59).
%n
%p
%P
%r
%R
%H:%M.
This format is a GNU extension.
%s
%S
00 through 60).
%t
%T
%H:%M:%S.
This format is a POSIX.2 extension.
%u
1 through
7), Monday being 1.
This format is a POSIX.2 extension.
%U
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
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.
%w
0 through
6), Sunday being 0.
%W
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
%X
%y
00 through
99). This is equivalent to the year modulo 100.
%Y
1 are numbered 0, -1, and so on.
%z
-0600 or +0100), or nothing if no time zone is
determinable.
This format is 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"'.
%Z
%%
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 content of the array
s is indetermined. 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 section Time Functions Example.
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 section 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 the network from a
different time zone, and would like times reported to you in the time zone
that local for you, rather than what is local for the computer.
In POSIX.1 systems the value of the TZ variable can be of 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:
std offset
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 or embedded digits, commas, or plus or 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 one 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:
std offset dst [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:
Jn
1 and 365.
February 29 is never counted, even in leap years.
n
0 and 365.
February 29 is counted in leap years.
Mm.w.d
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. If omitted, the default is
02:00:00.
For example, here is how one 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; see section Installing the GNU C Library). 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.
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 stay away
from modifying these strings. Modifying the strings will almost certainly
lead to trouble.
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.
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.
12).
This format is a GNU extension.
%m
01 through 12).
%M
00 through 59).
%n
%p
%P
%r
%R
%H:%M.
This format is a GNU extension.
%s
%S
00 through 60).
%t
%T
%H:%M:%S.
This format is a POSIX.2 extension.
%u
1 through
7), Monday being 1.
This format is a POSIX.2 extension.
%U
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
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.
%w
0 through
6), Sunday being 0.
%W
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
%X
%y
00 through
99). This is equivalent to the year modulo 100.
%Y
1 are numbered 0, -1, and so on.
%z
-0600 or +0100), or nothing if no time zone is
determinable.
This format is 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"'.
%Z
%%
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 content of the array
s is indetermined. 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 section Time Functions Example.
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 section 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 the network from a
different time zone, and would like times reported to you in the time zone
that local for you, rather than what is local for the computer.
In POSIX.1 systems the value of the TZ variable can be of 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:
std offset
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 or embedded digits, commas, or plus or 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 one 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:
std offset dst [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:
Jn
1 and 365.
February 29 is never counted, even in leap years.
n
0 and 365.
February 29 is counted in leap years.
Mm.w.d
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. If omitted, the default is
02:00:00.
For example, here is how one 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; see section Installing the GNU C Library). 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.
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 stay away
from modifying these strings. Modifying the strings will almost certainly
lead to trouble.
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.
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.
12).
This format is a GNU extension.
%m
01 through 12).
%M
00 through 59).
%n
%p
%P
%r
%R
%H:%M.
This format is a GNU extension.
%s
%S
00 through 60).
%t
%T
%H:%M:%S.
This format is a POSIX.2 extension.
%u
1 through
7), Monday being 1.
This format is a POSIX.2 extension.
%U
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
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.
%w
0 through
6), Sunday being 0.
%W
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
%X
%y
00 through
99). This is equivalent to the year modulo 100.
%Y
1 are numbered 0, -1, and so on.
%z
-0600 or +0100), or nothing if no time zone is
determinable.
This format is 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"'.
%Z
%%
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 content of the array
s is indetermined. 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 section Time Functions Example.
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 section 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 the network from a
different time zone, and would like times reported to you in the time zone
that local for you, rather than what is local for the computer.
In POSIX.1 systems the value of the TZ variable can be of 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:
std offset
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 or embedded digits, commas, or plus or 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 one 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:
std offset dst [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:
Jn
1 and 365.
February 29 is never counted, even in leap years.
n
0 and 365.
February 29 is counted in leap years.
Mm.w.d
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. If omitted, the default is
02:00:00.
For example, here is how one 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; see section Installing the GNU C Library). Other C libraries use their own
rule for choosing the default time zone, so there is little we can say
about them.