Jon Skeet spoke of the complexity of programming dates and times at the 2009 DevDays in London.
Can you give me an introduction to the ANSI C date/time functions on UNIX and indicate some of the deeper issues I should also consider when using dates and times?
Terminology
A date/time can be in two formats:
Data types
The date/time functions and types are declared in the time.h header file.
Time can be stored as a whole number or as an instance of a structure:
as a number using the time_t arithmetic type – to store calendar time as the number of seconds elapsed since the UNIX epoch January 1, 1970 00:00:00
using the structure timeval – to store calendar time as the number of seconds and nanoseconds elapsed since the UNIX epoch January 1, 1970 00:00:00
using the structure tm to store localtime, it contains attributes such as the following:
The tm_isdst attribute above is used to indicate Daylight Saving Time (DST). If the value is positive it is DST, if the value is 0 it is not DST.
Program to print the current Coordinated Universal Time
In the program above the function time reads the UNIX system time, subtracts that from January 1, 1970 00:00:00 (the UNIX epoch) and returns its result in seconds.
Program to print the current local time
In the program above the function localtime converts the elapsed time in seconds from the UNIX epoch into the broken-down time. localtime reads the UNIX environment TZ (through a call to the tzset function) to return the time relative to the timezone and to set the tm_isdst attribute.
A typical setting of the TZ variable in UNIX (using bash) would be as follows:
or
Program to print the current formatted Greenwich Mean Time
In the program above the function strftime provides specialised formatting of dates.
Other issues to consider