[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [leafnode-list] [ANNOUNCE:] leafnode-1.9.12



From: Cornelius Krasel <krasel@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>
> Joerg Dietrich wrote:

It occurred to me in my sleep that I hadn't answered clearly.
Nothing unusual in that, I can be quite obtuse.  Sorry!  Now 
that I look, I see I even bunged up the quote headers.  <blush>

You wanted to use mktime as the inverse of ctime.  The problem 
is that mktime, like ctime, works in local time.  This used to 
be clearer in the days when TZ defined any deviation from the 
hardware clock, since you could see why the conversion was 
different.  Now I see Linux doesn't need TZ set to get a time-
zone different from GMT. However, TZ is still the solution. 
You can set TZ inside your program and it will not change the 
user's time.  If you need to return TZ to the previous setting 
inside your program, then you have to save the intial value 
of TZ (handling the "not there" case) and set the value back 
to what it was. 

Here's your test program with the changes inserted: 
 

> #include <stdio.h>
> #include <time.h>
#include <stdlib.h>
#include <string.h> 

> int main( void ) {
>     time_t age;
>     time_t now;
>     struct tm * ltime;
>     int year;
>     int century;
>     struct tm timearray;
>
>     now = time( 0 );
>     ltime = localtime( &now );
>     year    = ltime->tm_year % 100;
>     century = ltime->tm_year / 100;
>
>     memset( &timearray, 0, sizeof(timearray) );
>     timearray.tm_year = year + (century*100);
>     timearray.tm_mon  = ltime->tm_mon;
>     timearray.tm_mday = ltime->tm_mday;
>     timearray.tm_hour = ltime->tm_hour;
>     timearray.tm_min  = ltime->tm_min;
>     timearray.tm_sec  = ltime->tm_sec;
>

    char *zone = getenv("TZ" );    // save current offset
    int len = 4 + (zone ? strlen(zone) : 0);
    char *oldzone = (char*)calloc( len, 1 );
    snprintf( oldzone, len, "TZ=%s", zone ? zone : "" );
    putenv( "TZ=GMT0" );            // use mktime to create UTC
 
>     age = mktime( &timearray ) - ltime->tm_gmtoff;

    // Restoring the original timezone is optional
    // because putenv makes internal changes only.
    //
    putenv(oldzone);
    free(oldzone);

>     if ( ltime->tm_isdst ) {
> age = age - 3600;
>     }
>
>     printf("Old time  : %ld\n", now );
>     printf("New time  : %ld\n", age );
>     if ( ( now - age ) != 0 ) {
> printf("Difference: %ld\n", now-age );
>     }
>     printf("Offset: %ld\n", ltime->tm_gmtoff );
>
>     exit(0);
> }


--
Oisin  "Curly++"  Curtin                     ocurtin@SPAM@usa.net
Surface Liaison, Minetown Digger                    Send no SPAM@
                                http://pages.infinit.net/curlypp/



-- 
leafnode-list@xxxxxxxxxxxxxxxxxxxxxxxxxxxx -- mailing list for leafnode
To unsubscribe, send mail with "unsubscribe" in the subject to the list