struct tm -> time_t converter wanted

Steve Summit scs at athena.mit.edu
Tue Oct 18 16:05:56 AEST 1988


In article <442 at grand.UUCP> day at grand.UUCP (Dave Yost) writes:
>I was surprised to find no routine in the C library
>to convert a struct tm into a time_t.  Is there
>such a routine floating around somewhere?

Here's mine.  You may have to uncomment the dysize() routine at
the end (but not on BSD systems, which already have this function in
ctime.o in libc.a).  Also -DBSD4_2, if necessary, to find
<time.h> correctly.  (Ditto previous requests in this newsgroup
for more consistency in #include file naming, or, since it's too
late for that, some good way of dealing with the resulting
confusion.)

Since either tm_yday or the pair tm_mon,tm_mday uniquely
determine the day, I think you're supposed to set the ones you don't
know to -1.

There may be a better way to figure out DST correction than
calling localtime() again, but I don't know it.

                                            Steve Summit
                                            scs at adam.pika.mit.edu

--------------------------unlocaltime.c--------------------------
/*
 *  Convert a struct tm (actually, a pointer thereto) back to a
 *  time_t, essentially performing the inverse of localtime().
 *
 *  Written by Steve Summit in October, 1985.
 *  Please keep this comment if you keep this code.
 */

#include <sys/types.h>
#ifndef BSD4_2
#include <time.h>
#else
#include <sys/time.h>
#endif
#include <sys/timeb.h>

#define TRUE 1
#define FALSE 0

struct tm *localtime();

static int dmsize[12] =
	{
	31,
	28,
	31,
	30,
	31,
	30,
	31,
	31,
	30,
	31,
	30,
	31
	};

time_t
unlocaltime(tm)
struct tm *tm;
{
time_t timbuf;
struct timeb info;
int year;
int i;
int fillin;

struct tm *tm2;

ftime(&info);

timbuf = 0;

year = tm->tm_year + 1900;

for(i = 1970; i < year; i++)
	timbuf += dysize(i);

if(tm->tm_yday == -1)
	{
	tm->tm_yday = 0;

	for(i = 0; i < tm->tm_mon; i++)
		tm->tm_yday += dmsize[i];

	/* Leap year */

	if (dysize(year) == 366 && tm->tm_mon >= 2)
		tm->tm_yday++;

	tm->tm_yday += tm->tm_mday - 1;		/* mday is 1 based */

	fillin = FALSE;
	}
else	fillin = TRUE;

timbuf = (((timbuf + tm->tm_yday) * 24 + tm->tm_hour) * 60 +
				tm->tm_min + info.timezone) * 60 + tm->tm_sec;

timbuf -= 60 * 60;

tm2 = localtime(&timbuf);

if(!tm2->tm_isdst)
	timbuf += 60 * 60;

tm->tm_wday = tm2->tm_wday;

if(fillin)
	{
	tm->tm_mon = tm2->tm_mon;
	tm->tm_mday = tm2->tm_mday;
	}

return(timbuf);
}

/*
dysize(y)
int y;
{
if((y % 4) == 0)
	return(366);
return(365);
}
*/



More information about the Comp.lang.c mailing list