I recently had to come up with a workaround to mktime() on an old
SCO Xenix box on which mktime() was unavailable. Plenty of
algorithms to convert from a string representation of a date/time
to a time_t are floating around on the 'net, but most will only
get you close, usually screwing up on transitions to and from
Daylight Saving Time. Fortunately, the following let me get
around all that, and I found it "fast enough". If I get some
time, I might convert this to a real mktime() substitute for
those pre-ANSI C systems which don't have mktime(). There's
plenty of them still around, you know, often dedicated machines
running ancient vertical-market software that won't run on Linux!
/* strtotime.c: convert string datetime to time_t using binary search
by Joe Foster 1996
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* arg format is ccyymmdd[hhmmss]
*/
main(int argc, char** argv)
{
int i;
for (i = 1; i < argc; i++) {
int year = 1900, month = 1, day = 1, hour = 0, min = 0, sec = 0;
char target[16];
time_t lbound = 0, ubound = 0x7fffffff, mid;
sscanf(argv[i], "%4d%2d%2d%2d%2d%2d",
&year, &month, &day, &hour, &min, &sec);
sprintf(target, "%04d%02d%02d%02d%02d%02d",
year, month, day, hour, min, sec);
fprintf(stderr, "arg %d = %04d-%02d-%02d %02d:%02d:%02d = %s\n",
i, year, month, day, hour, min, sec, target);
while (lbound <= ubound) {
struct tm* tp;
char attempt[16];
int r;
/* when a straight add might overflow... */
mid = ((lbound >> 1) + (ubound >> 1)) | (lbound & ubound & 1);
tp = localtime(&mid);
sprintf(attempt, "%04d%02d%02d%02d%02d%02d",
tp->tm_year + 1900, tp->tm_mon + 1, tp->tm_mday,
tp->tm_hour, tp->tm_min, tp->tm_sec);
fprintf(stderr, "mid = %s = %ld\n", attempt, (long)mid);
if (!(r = strcmp(target, attempt))) break; /* found it! */
else if (r < 0) ubound = mid - 1; /* guess was too high */
else if (r > 0) lbound = mid + 1; /* guess was too low */
else abort(); /* This had better be dead code! */
}
printf("%s = %ld\n", target, (long)mid);
}
return 0;
--Quote:}
WARNING: I cannot be held responsible for the above They're coming to
because my cats have apparently learned to type. take me away, ha ha!