Thread: How many times can time variables be delcared?

  1. #1
    Registered User
    Join Date
    May 2003
    Posts
    30

    How many times can time variables be delcared?

    Hi, Iam trying to compare to random dates/times but am unable to create 2 independent times as it wont let me decalre 2 individual time_t variables, it will just overight the first variable with the second one.

    Is it not possible to create 2 indivudual random dates/time based on systemtime modify one and the other is not changed?

    If it is possible could someone tell me how I am to initialise it correctly, as at the momoent I am using:

    Code:
    #include<iostream>
    #include<string>
    #include<time.h>
    
    using namespace std;
    
    int main()
    {
        char t1[123];
        char t2[123];
        time_t time1 = time(NULL);
        time_t time2 = time(NULL) + (a constant);
        tm *ltime1 = gmtime(&time1);
        tm *ltime = gmtime(&time2);
        strtime(t1,123,"%a,%b,%Y", ltime1);
        strtime(t1,123,"%a,%b,%Y", ltime2);
        cout<<t1<<endl;
        cout<<t2<<endl;
        return 0;
    }
    Thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    gmtime() returns a pointer to its OWN internal memory (its always the same pointer)
    You need to copy the result, not just point at it
    Code:
        tm ltime1 = *gmtime(&time1);
        tm ltime2 = *gmtime(&time2);
        strtime(t1,123,"%a,%b,%Y", &ltime1);
        strtime(t2,123,"%a,%b,%Y", &ltime2);
    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.

  3. #3
    Registered User
    Join Date
    May 2003
    Posts
    30
    Thanks Salem I understand now, your a life save.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with time
    By Gong in forum C++ Programming
    Replies: 7
    Last Post: 01-11-2007, 02:43 PM
  2. need help in time zone
    By Gong in forum C++ Programming
    Replies: 2
    Last Post: 01-03-2007, 04:44 AM
  3. The Timing is incorret
    By Drew in forum C++ Programming
    Replies: 5
    Last Post: 08-28-2003, 04:57 PM
  4. I apologize. Good bye.
    By doubleanti in forum A Brief History of Cprogramming.com
    Replies: 14
    Last Post: 05-03-2002, 06:51 PM
  5. relating date....
    By Prakash in forum C Programming
    Replies: 3
    Last Post: 09-19-2001, 09:08 AM