user1612986
user1612986

Reputation: 1415

c++ time_t going back before 1/1/1970

i have a c++ code by which i can compute/manipulate starting from an input excel date (by manipulate i mean i can increase/decrease the input date by specific increments or do other computations on it).

i use the variable time_t in my code. accroding to msdn documentation time_t is the number of seconds elaspsed since 01/01/1970. so given an input date i first compute the elasped seconds since 01/01/1970, store it in a time_t vcariable and later use localtime() for all other computation.

my code works fine as along as my input date is more than 01/01/1970 but breaks down for dates before that.

question: is there any other variable or structure using which i can go before 01/01/1970. or is there a way to manipulate the time_t variable to go before 01/01/1970.

thanks in advance

i start with 02/01/1970. i want to decrease the month by 2. first i use

void localtime(int* py = 0, int* pm = 0, int* pd = 0, 
            int* ph = 0, int* pn = 0, int* ps = 0,
            int* pwday = 0, int* pyday = 0, int* pisdst = 0) const
{
    struct tm* ptm = ::localtime(&t_); 
    if (py) *py = ptm->tm_year + 1900;
    if (pm) *pm = ptm->tm_mon + 1;
    if (pd) *pd = ptm->tm_mday;
    if (ph) *ph = ptm->tm_hour;
    if (pn) *pn = ptm->tm_min;
    if (ps) *ps = ptm->tm_sec;
    if (pwday) *pwday = ptm->tm_wday;
    if (pyday) *pyday = ptm->tm_yday;
    if (pisdst) *pisdst = ptm->tm_isdst;
}

then i use: maketime(y, m + count, d, h, n, s); where y=1970, m=2, count=-2, d=1 (from the output of the above code. the maketime() is as follows:

void maketime(int y, int m, int d, int h = 0, int n = 0, int s = 0)
{
    struct tm t;
    t.tm_year = y - 1900;
    t.tm_mon  = m - 1;
    t.tm_mday = d;
    t.tm_hour = h;
    t.tm_min  = n;
    t.tm_sec  = s;
    t.tm_isdst = -1;

    t_ = ::mktime(&t);
}

this results in t_ =-1.

now on this result i call localtime() again and

     struct tm* ptm = ::localtime(&t_);  

the first line inside localtime() fails when t_ = -1.

Upvotes: 4

Views: 2074

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308452

FILETIME is similarly based on an integer count, 100-nanosecond intervals in this case, and it goes all the way back to 1601.

After seeing your edit, the problem seems simple: you need to make sure all of the elements of the tm struct are within bounds. When you add or subtract months, you need to adjust until the month number is between 0 and 11. This is the case whether you're using time_t or FILETIME.

while (m < 0)
{
    m += 12;
    y -= 1;
}
while (m > 11)
{
    m -= 12;
    y += 1;
}

I'm not sure what will happen if the day exceeds the number of days in a month, for example if you try to subtract 1 month from March 31.

Upvotes: 3

Related Questions