Thread: Hi First time poster, big time problem with my program! Regarding epoch time conver

  1. #1
    Registered User
    Join Date
    Apr 2013
    Posts
    3

    Hi First time poster, big time problem with my program! Regarding epoch time conver

    Hi guys,

    First time poster, was hoping to get a bit of help with my code. Im wondering if this is a legal operation with a for loop.
    Code:
        edays = tv->tv_sec / 86400;                 // Turn into days since epoch
    
    
    
    
        fouryears = edays / days4years;
        remaindays = edays % days4years;            // Determines which 4 year perio
        tempdays = remaindays;
    
    
        for (monthindex = 0 ; tempdays <= 0 ; monthindex++)
        {
            daysgoneby += months[monthindex].day;   // Keeps track of days passed
    
    
            tempdays -= months[monthindex].day;
    
    
            if (monthindex > 11)                    // Resets counter for 12 months
            {
                monthindex = 0;
            }
            ++monthtracker;
        }
    Can I have a different paramter (in this case tempdays) in the for loop with the other parameter type ( monthindex) ? Also My loop is acting funny, this is just a partition of code.

    Question 2: Problem with the loop. Bascially tempdays has a positive value of 12011 or so and so it enters the forloop. This particular code/ program is called upon in a modulation setup by another program to provide the date and time. So on the first call from the main program, my month tracker value is 0, which means monthtracker gets initialized to 0, but does NOT go through the loop...as it does not get incremented properly. Meaning the loop must exit almost immediately? The next subsequent calls by the main program give my monthtracker values of -124959595 or so....basically nonsense and I can't figure it out. I've been on this for about 5 hours now and I'd really like to figure it out.

    If more clarification is needed i'll gladly post the entire program (just this one not the other calling program).

    Code:

    Code:
    #include <curses.h>
    #include <sys/time.h>
    #include <time.h>
    #include "fmttime.h"                    // Include for formattime interface
    #include <strstream>
    #include <iostream>
    #include <iomanip>
    
    
    static int monthindex;                  // Lookup table index
    static const int milli = 1000;          // Constant value for ms conversion
    static const int epochyear = 1970;      // Epoch year 1970
    static const int leapy = 4;             // Number of years for a leapyear
    using namespace std;
    
    
    struct Monthpairs                       // Fields for month & day lookup table
    {
        const char* mon;                    // Months
        int day;                            // Days
    };
    
    
    Monthpairs months[] =                   // Lookup table for months & days
    {
        {"Jan", 31},
        {"Feb", 28},
        {"Mar", 31},
        {"Apr", 30},
        {"May", 31},
        {"Jun", 30},
        {"Jul", 31},
        {"Aug", 31},
        {"Sep", 30},
        {"Oct", 31},
        {"Nov", 30},
        {"Dec", 31},
    };
    
    
    // Structure which will contain the human readable local
    // time values
    struct ExpandedTime
    {
    
    
        int et_usec;        // Number of Milliseconds local time
        int et_sec;         // Number of Seconds local time
        int et_min;         // Number of minutes local time
        int et_hour;        // Number of hours local time
        int et_day;         // Day of the month local time
        int et_mon;         // Month of the year local time
        int et_year;        // Our current year (2013 present)
    
    
    };
    
    
    // Function prototype for Expanded time function
    
    
    ExpandedTime* localTime(struct timeval* tv, ExpandedTime* etime);
    
    
    // Expanded time will take the Epoch time and convert into days,
    // months years, hours, minutes etc and then store this back into
    // the Expanded Structure
    
    
    ExpandedTime* localTime(
                            struct timeval* tv,     // Pointer to timeval struct
                            ExpandedTime* etime     // '' '' to expandedtime strct
                            )
    {
        tzset();                                    // Corrects for timezone
    
    
        int epochT = (tv->tv_sec) - timezone;       // Epoch seconds with
        int epochUT = tv->tv_usec;                  // epochtime microseconds
        int edays;                                  // Days since epochtime
        int days4years = 1461;                      // Number of days in 4 years
        int fouryears;                              // Number of 4 year periods
        int remaindays;                             // Number of days leftover
        int tempdays;                               // Holds value of remaindays
        int monthtracker;                           // Number of TOTAL months passed
                                                    // since current 4 year period
        int daysgoneby;                             // Number of days passed
                                                    // since current 4 year period
    
    
        etime->et_usec = (epochUT/milli) % milli;   // Find the milliseconds
    
    
        etime->et_sec = epochT % 60;
        epochT /= 60;                               // Turn into minutes
    
    
        etime->et_min = epochT % 60;
        epochT /= 60;                               // Turn into hours
    
    
        if (localtime(&tv->tv_sec)->tm_isdst !=0)
            etime->et_hour = (epochT % 24) + 1;     // Hours with DST correction
        else
            etime->et_hour = (epochT % 24);
    
    
        edays = tv->tv_sec / 86400;                 // Turn into days since epochT
    
    
    
    
        fouryears = edays / days4years;
        remaindays = edays % days4years;            // Determines which 4 year perio
        tempdays = remaindays;
    
    
        for (monthindex = 0 ; tempdays <= 0 ; monthindex++)
        {
            daysgoneby += months[monthindex].day;   // Keeps track of days passed
    
    
            tempdays -= months[monthindex].day;
    
    
            if (monthindex > 11)                    // Resets counter for 12 months
            {
                monthindex = 0;
            }
            ++monthtracker;
        }
        etime->et_day = tempdays + months[monthsindex];
    
    
    // This will take the number of months passed in current 4 year period
    // and add it to the epoch year of 1970 to find the current year
    
    
        etime->et_year = (monthtracker % 12)  + epochyear;
        return etime;
    
    
    }
    
    
    // Formats epoch time passed from a main function to a
    // human readable string
    
    
    char* formatTime(
                    struct timeval* tv,     // Pointer to timeval struct
                    char* buf,              // Pointer to char buf
                    size_t len              // size of buffer
                    )
    {
        struct ExpandedTime etime2;         // Struct object declaration
    
    
    
    
        // Array containing strings for the months
    
    
    /*    const char* month[] =
            {NOT USED OLD CODE BUT LEFT IN JUST IN CASE
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
            "Aug", "Sep", "Oct", "Nov", "Dec"
            };*/
    
    
    
    
        if (len > 0)                        // Will only print to valid sized buffer
        {
            localTime(tv, &etime2);
            ostrstream oss(buf, len);
    
    
            // Prints the time and date into a human readable string and
            // places it in the supplied buffer from plot.cc
    
    
            oss << etime2.et_year << " " <<  months[monthindex].mon << " " <<
            etime2.et_day << " " << setw(2) << etime2.et_hour << ":"
            << setfill('0') << setw(2) << etime2.et_min << ":" << setfill('0')
            << setw(2) << etime2.et_sec << ":" << setfill('0') << setw(3) <<
             etime2.et_usec << ends;
        }
    
    
        else if (len <= 0)
        {
            cout << "Sorry the length of the buffer is too small cannot write" << en
        }
    
    
        return buf;
    }
    *EDIT* Sorry I just realized I have the operator in the for loop backwards...should be > 0. My question regarding that forloop still stands however, but I need to test if this might resolve my problem. Thanks for looking. If one could check that the logic of finding the year and month using my lookup table is sound I'd be very appreciative. Thanks again!
    Last edited by RyanKim; 04-17-2013 at 12:11 AM.

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,633
    First please be careful with this header <strstream>. This is an old, pre-standard header that is quite different that the standard <sstream> header.

    First time poster, was hoping to get a bit of help with my code. Im wondering if this is a legal operation with a for loop.
    Is it doing what you want? It appears to be legal code, but perhaps a while or do/while might be easier to understand the logic.?

    Also I see a lot of integer math, don't forget that there are no fractions when dealing with integer math.

    which means monthtracker gets initialized to 0, but does NOT go through the loop...as it does not get incremented properly. Meaning the loop must exit almost immediately? The next subsequent calls by the main program give my monthtracker values of -124959595 or so....basically nonsense and I can't figure it out. I've been on this for about 5 hours now and I'd really like to figure it out.
    It looks like you need to initialize this variable to some known value. Remember you must assign a value to your variables before you try to use them.

    Jim

  3. #3
    Registered User
    Join Date
    Apr 2013
    Posts
    3
    Thanks for the reply. I am aware of the archaicness of strstream. I had a question regarding integer math. If i take 4/3 i get 1.3333333, does C handle that as 1? What about 1.8? I assume C jsut trashes the remainder or decimal value away and keeps the whole number only? so to reiterate 5.9 is just 5?

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by RyanKim
    If i take 4/3 i get 1.3333333, does C handle that as 1?
    You can write an extremely simple program to find out instead of asking. But yes, integer division results in such truncation. Also, this is C++. What's C?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Apr 2013
    Posts
    3
    Is there anyone who can perhaps run my code throught their head on just a particular part? I'll explain everything, as well as post the revised code. I've been dealing with this for 5 hours now and yet to resolve it.

    Code:
    #include <curses.h>
    #include <sys/time.h>
    #include <time.h>
    #include "fmttime.h"                    // Include for formattime interface
    #include <strstream>
    #include <iostream>
    #include <iomanip>
    
    
    static int monthindex;                  // Lookup table index
    static const int milli = 1000;          // Constant value for ms conversion
    static const int epochyear = 1970;      // Epoch year 1970
    static const int leapy = 4;             // Number of years for a leapyear
    using namespace std;
    
    
    struct Monthpairs                       // Fields for month & day lookup table
    {
        const char* mon;                    // Months
        int day;                            // Days
    };
    
    
    Monthpairs months[] =                   // Lookup table for months & days
    {
        {"Jan", 31},
        {"Feb", 28},
        {"Mar", 31},
        {"Apr", 30},
        {"May", 31},
        {"Jun", 30},
        {"Jul", 31},
        {"Aug", 31},
        {"Sep", 30},
        {"Oct", 31},
        {"Nov", 30},
        {"Dec", 31},
    };
    
    
    // Structure which will contain the human readable local
    // time values
    struct ExpandedTime
    {
    
    
        int et_usec;        // Number of Milliseconds local time
        int et_sec;         // Number of Seconds local time
        int et_min;         // Number of minutes local time
        int et_hour;        // Number of hours local time
        int et_day;         // Day of the month local time
        int et_mon;         // Month of the year local time
        int et_year;        // Our current year (2013 present)
    
    
    };
    
    
    // Function prototype for Expanded time function
    
    
    ExpandedTime* localTime(struct timeval* tv, ExpandedTime* etime);
    
    
    // Expanded time will take the Epoch time and convert into days,
    // months years, hours, minutes etc and then store this back into
    // the Expanded Structure
    
    
    ExpandedTime* localTime(
                            struct timeval* tv,     // Pointer to timeval struct
                            ExpandedTime* etime     // '' '' to expandedtime strct
                            )
    {
        tzset();                                    // Corrects for timezone
    
    
        int epochT = (tv->tv_sec) - timezone;       // Epoch seconds with
        int epochUT = tv->tv_usec;                  // epochtime microseconds
        int edays;                                  // Days since epochtime
        int days4years = 1460;                      // Number of days in 4 years
        int fouryears;                              // Number of 4 year periods
        int remaindays;                             // Number of days leftover
        int tempdays;                               // Holds value of remaindays
    
    
        int monthtracker = 0;                       // Number of TOTAL months passed
                                                    // since current 4 year period
        int daysgoneby = 0;                         // Number of days passed
                                                    // since current 4 year period
    
    
        etime->et_usec = (epochUT/milli) % milli;   // Find the milliseconds
        etime->et_sec = epochT % 60;
        epochT /= 60;                               // Turn into minutes
    
    
        etime->et_min = epochT % 60;
        epochT /= 60;                               // Turn into hours
    
    
        if (localtime(&tv->tv_sec)->tm_isdst !=0)
            etime->et_hour = (epochT % 24) + 1;     // Hours with DST correction
        else
            etime->et_hour = (epochT % 24);
    
    
        edays = tv->tv_sec / 86400;                 // Turn into days since epoch
    
    
    
    
        fouryears = edays / days4years;
        remaindays = edays % days4years;            // Determines which 4 year perio
        tempdays = remaindays;
    
    
        for (monthindex = 0 ; tempdays >= 0 ; ++monthindex)
        {
            daysgoneby += months[monthindex].day;   // Keeps track of days passed
    
    
            tempdays -= months[monthindex].day;
    
    
            if (monthindex >= 11)                   // Resets counter for 12 months
            {
                monthindex = 0;
            }
            ++monthtracker;
        }
    
    
        etime->et_day = monthindex; // (tempdays + months[monthindex].day);
    
    
    // This will take the number of months passed in current 4 year period
    // and add it to the epoch year of 1970 to find the current year
    
    
        etime->et_year = (monthtracker / 12)  + (fouryears * 4) + epochyear;
    
    
        return etime;
    
    
    }
    // Formats epoch time passed from a main function to a
    // human readable string
    
    
    char* formatTime(
                    struct timeval* tv,     // Pointer to timeval struct
                    char* buf,              // Pointer to char buf
                    size_t len              // size of buffer
                    )
    {
        struct ExpandedTime etime2;         // Struct object declaration
    
    
        if (len > 0)                        // Will only print to valid sized buffer
        {
            localTime(tv, &etime2);
            ostrstream oss(buf, len);
    
    
            // Prints the time and date into a human readable string and
            // places it in the supplied buffer from plot.cc
    
    
            oss << etime2.et_year << " " <<  months[monthindex].mon << " " <<
            etime2.et_day << " " << setw(2) << etime2.et_hour << ":"
            << setfill('0') << setw(2) << etime2.et_min << ":" << setfill('0')
            << setw(2) << etime2.et_sec << ":" << setfill('0') << setw(3) <<
             etime2.et_usec << ends;
        }
    
    
        else if (len <= 0)
        {
            cout << "Sorry the length of the buffer is too small cannot write" << en
        }
    
    
        return buf;
    }
    Basically the problem arises at the for loop. Using a value of "tempdays" = 1212, I expect my "monthindex" to be 3 and my "tempdays variable to be" -3. Monthindex = 3 will point to the correct month in the table which should be april. Instead I get august and a corresponding monthindex of 7. As for tempdays I get -2 instead of -3. I just have no clue as to what im doing wrong here...obviously monthindex is incrememting an extra 4 times I just don't know why.

    Oh and my monthtracker variable is essentially a counter that keeps track of how many months of the table i run through, and i get 40 which is correct. meaning it goes throught the table a total of 3 times (36 months) plus 4 months = 40.
    Last edited by RyanKim; 04-17-2013 at 03:29 PM. Reason: Forgot some info

  6. #6
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Quote Originally Posted by RyanKim View Post
    Basically the problem arises at the for loop. Using a value of "tempdays" = 1212, I expect my "monthindex" to be 3 and my "tempdays variable to be" -3. Monthindex = 3 will point to the correct month in the table which should be april. Instead I get august and a corresponding monthindex of 7. As for tempdays I get -2 instead of -3. I just have no clue as to what im doing wrong here...obviously monthindex is incrememting an extra 4 times I just don't know why.

    Oh and my monthtracker variable is essentially a counter that keeps track of how many months of the table i run through, and i get 40 which is correct. meaning it goes throught the table a total of 3 times (36 months) plus 4 months = 40.
    This sounds like a perfect time to use the debugger that your IDE probably comes with. Set a breakpoint on the first line inside the for loop and inspect the variables each iteration through the loop. Keep track of what you expect them to be vs. what they actually are. You'll probably need to go through the loop 12 times to see the problem.
    Last edited by Cat; 04-17-2013 at 11:45 PM.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. operator!= and primary-expression error : First time poster
    By kentrenholmpei in forum C++ Programming
    Replies: 2
    Last Post: 11-04-2011, 06:24 AM
  2. Replies: 23
    Last Post: 05-22-2011, 11:20 PM
  3. time program showing time since epoch?
    By cus in forum Linux Programming
    Replies: 5
    Last Post: 01-10-2009, 01:56 PM
  4. Epoch and quantum and time slices ??
    By pritesh in forum Linux Programming
    Replies: 0
    Last Post: 02-18-2002, 08:55 AM