🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #2198

Re: timezone info left out of time.h?

#2198
From: Paul Eggert
Date: Fri, 02 Oct 1992 22:43
59 lines
2099 bytes
pds@lemming.webo.dg.com (Paul D. Smith) writes:

	as far as I can see it is impossible to determine the timezone
	offset in a standard way.  This also means that given a struct
	tm filled with UTC time you cannot standardly (new word :)
	convert it into a time_t.

It's not trivial, but it's possible: just take the difference between
localtime and gmtime, as shown below.  Once you have this, it's fairly
easy to use mktime to convert a UTC struct tm to time_t -- but watch out
for integer overflow!

/* Figure out which time zone you're in.  */
/* Most of this code will be distributed as part of RCS.  */
/* Copyright 1992 by Paul Eggert */

#include <time.h>

#define TM_YEAR_ORIGIN 1900

static long difftm(struct tm const *, struct tm const *);

/* Set *ZONE to the number of seconds east of GMT.
   Yield 0 if successful, -1 otherwise.  */
int
timezone_offset(long *zone)
{
	time_t now;
	struct tm *t, gmt;

	if (time(&now) == -1 || !(t = gmtime(&now)))
		return -1;
	gmt = *t;
	*zone = difftm(localtime(&now), &gmt);
	return 0;
}

/* Yield A - B, measured in seconds.  */
static long
difftm(struct tm const *a, struct tm const *b)
{
	int ay = a->tm_year + (TM_YEAR_ORIGIN - 1);
	int by = b->tm_year + (TM_YEAR_ORIGIN - 1);
	return
		(
			(
				(
					/* difference in day of year */
					   a->tm_yday - b->tm_yday
					/* + intervening leap days */
					+  ((ay >> 2) - (by >> 2))
					-  (ay/100 - by/100)
					+  ((ay/100 >> 2) - (by/100 >> 2))
					/* + difference in years * 365 */
					+  (long)(ay-by) * 365
				)*24 + (a->tm_hour - b->tm_hour)
			)*60 + (a->tm_min - b->tm_min)
		)*60 + (a->tm_sec - b->tm_sec);
}
Technical Details
Message-ID: <bj`Nr6`x@twinsun.com>
Path: arc1-ca.pugleaf.net!sparky!uunet!sun-barr!ames!elroy.jpl.nasa.gov!ucla-cs!twinsun!eggert
References: <PDS.92Oct1193222@lemming.webo.dg.com>

Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c
Path: arc1-ca.pugleaf.net!sparky!uunet!sun-barr!ames!elroy.jpl.nasa.gov!ucla-cs!twinsun!eggert
From: eggert@twinsun.com (Paul Eggert)
Subject: Re: timezone info left out of time.h?
Message-ID: <bj`Nr6`x@twinsun.com>
Sender: usenet@twinsun.com
Nntp-Posting-Host: farside
Organization: Twin Sun, Inc
References: <PDS.92Oct1193222@lemming.webo.dg.com>
Date: Fri, 2 Oct 1992 22:43:24 GMT
Lines: 59