Getting local and greenwich time

This is a discussion on Getting local and greenwich time within the C Programming forums, part of the General Programming Boards category; Hello, In the following code, I try to get the local time and greenwich time and find the difference between ...

  1. #1
    Registered User
    Join Date
    Aug 2010
    Posts
    2

    Getting local and greenwich time

    Hello,
    In the following code, I try to get the local time and greenwich time and find the difference between them. But the output shows both the time values are equal:
    diff=0 iTm1=16:34 iTm2=16:34 <-----[gmtime is 13:34 actualy]

    When I just retreive gmtime, it works correctly. But when I retreive both local and gmtime, gmtime becomes equal to localtime.


    Code:
    #include <stdio.h>
    #include <time.h>
    int main()
    {
            time_t iTime;
            struct tm * iTm1;
            struct tm * iTm2;
            int iTimeDifferenceInMinutes;
    
            time(&iTime);
            iTm1=gmtime(&iTime);
            iTm2=localtime(&iTime);
            iTimeDifferenceInMinutes=(int)((iTm2->tm_hour - iTm1->tm_hour)) * 60;
            printf("diff=%d iTm1=%d:%d iTm2=%d:%d\n", iTimeDifferenceInMinutes,
                            iTm1->tm_hour, iTm1->tm_min,
                            iTm2->tm_hour, iTm2->tm_min);
    }
    I have a mistake but I couldn't find it...
    May someone show me my fault please..?
    Thanks.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,437
    iTm1=gmtime(&iTime);
    iTm2=localtime(&iTime);
    These return a POINTER to some internal data within the time handing routines.

    You need to make a copy of that before calling again.

    Eg.
    struct tm iTm1 = *gmtime(&iTime);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Aug 2010
    Posts
    2
    Quote Originally Posted by Salem View Post
    iTm1=gmtime(&iTime);
    iTm2=localtime(&iTime);
    These return a POINTER to some internal data within the time handing routines.

    You need to make a copy of that before calling again.

    Eg.
    struct tm iTm1 = *gmtime(&iTime);
    Thank you.That solved my problem.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21