[net.lang.c] ANSI's time_t

rbutterworth@watmath.UUCP (Ray Butterworth) (01/09/86)

The ANSI standard defines time_t as a system-dependent value which
stores a date (and time).  There is a function time() which returns
the time_t value of the current time.  There is a function difftime()
which gives the number of seconds between two time_t values.  There
are funtions gmtime() and localtime() which will take a time_t value
and convert them to a tm structure which has individual fields for
the values of the year, hour, etc.  And there are functions ctime()
and asctime() for converting the time_t and tm structure into human-
format dates.

Notice what is missing?  There is only one way of generating a time_t
value, i.e. time().

There isn't an inverse of difftime() which would allow one to generate
a time_t value N seconds in the future or past

And even worse, there isn't an inverse of localtime() or gmtime() which
will convert a tm structure into a time_t.  i.e. there is no reasonable
way to portably determine the time_t value of a given date.

One could of course set the system clock to the required date and time,
call time(), and quickly set the system clock back to the correct value
before anyone notices.  Not a very good solution.

The alternative is to guess a value for time_t for the given date,
call localtime() on it and see how close we came.  If we aren't
close enough, guess again.  A binary search could be used to determine
the correct time_t value in 30 or so iterations, but that assumes that
time_t is an increasing (or decreasing) function of the time, something
which isn't guaranteed by the standard.  This isn't a very good solution
either, but at least I don't have to be privileged to use it.

Now, I have to write a function for generating the time_t value for
arbitrary dates (assuming that those dates are representable by
time_t of course), and the binaray search is the best method I could
come up with.  Am I missing something, or is the ANSI standard missing
something, or what?

rlk@chinet.UUCP (Richard L. Klappal) (01/11/86)

Rochkind's book 'ADVANCED UNIX PROGRAMMING' (ISBN 0-13-011800-1) gives
a sample routine to convert "yymmddhhmmss" to internal format. (pp51++).
It not elegant, just brute strength & ugliness, but it works.  The
other routines (difftime, delta_days, day_of_year, etc.) are trivail,
or already available as part of ctime.

-- 
---
UUCP: ..!ihnp4!chinet!uklpl!rlk || MCIMail: rklappal || Compuserve: 74106,1021
---

tim@ism780c.UUCP (Tim Smith) (01/17/86)

Re: binary search to get time_t for a given time

I needed to do this once, and ended up doing what you suggest.  It
certainly is a kludge.  I agree that there should be a function to
do this.  Please, ANSI, include one.

-- 
Tim Smith       sdcrdcf!ism780c!tim || ima!ism780!tim || ihnp4!cithep!tim