may be simple but i don't know -- Print current date from C program

How to print current date of the Unix system accessing thru C++ program ?

I wrote like this

#include <time.h>
.......
time_t tt;
struct tm *tod;
....
time(&tt);
tod = localtime(&tt);
cout << tod->tm_mon + 1 << "/"
<< tod->tm_mday << "/"
<< tod->tm_year << endl;

Still the year/ date /month printed is not correct

The asctime(tod) prints Fri Feb 15 05:49:29 2002 the correct date

But the cout << tod->tm_mon / tm_mday / tm_year prints wrong values only
The output is like
2/17/146

which has not correspondance with Feb 15/ 2002 date

Please help

Thanks

I just tried your code and I got:
2/15/102
which is the expected result since today is Feb 15, 2002.

Just as you are adding 1 to tm_mon, so must you add 1900 to tm_year.

If you are really getting 2/17/146, you must have a bug elsewhere.

Yes. This seems to be really funny.
I am getting the same result ie "2/17/146" only.

The date in command prompt gives correct date
Fri Feb 15 07:22:05 CST 2002

But when accessing from C program, I get the 2/17/146 result.

Is there any other environmental set up like <locale.h > inside my C program ?
or can we achieve the same by using getdate()

Thanks
LS1429

Here is my test program:

#include<iostream.h>
#include<time.h>
main()
{
        time_t tt;
        struct tm *tod;
        time(&tt);
        tod=localtime(&tt);
        cout << tod->tm_mon +1 << "/" << tod->tm_mday << "/"
             << tod->tm_year << endl ;
        exit(0);
}

Give it a try. I am getting 2/15/102 without doing anything more. Internally the library will at my TZ environment variable but that's the only other thing that can affect the output that I know of.

And by the way, I tested on a Sun. What system are you using?

I found one difference from my code from yours.

I am using the tm structure in a function instead of main()
My sample code structure is

#include <iostream.h>
#include <iomanip.h>
#include <time.h>
....
int main(int argc, char **argv)
{
.....
display_estHdr_formatted(msg);
.....
}

int displayHdr(istrstream& msg)
{

time_t tt;                 // Seconds since 1/1/1970 
struct tm *tod; 

time\(&tt\);
tod = localtime\(&tt\);

     cout &lt;&lt; tod-&gt;tm_mon \+ 1     &lt;&lt; "/" 
      &lt;&lt; tod-&gt;tm_mday        &lt;&lt; "/"  
      &lt;&lt; tod-&gt;tm_year        &lt;&lt; endl
	  &lt;&lt; tod-&gt;tm_sec			&lt;&lt; endl;


msg.read\(displayBuffer,424\);

msg.read\(displayBuffer, 9\);

return 0;

}

I am using IBM Aix version

Did you try my program? Did it work?

Thanks.

Your program worked and when embedded in my program as individual function it was continuing the same.

The actual problem was before call of the function, I have converted an output to octal which has set the o/p to octals.

Hence octal 146 corresponds to 102 (year 1900 +102) decimal
and hence I was receiving the date in octal.

:slight_smile:

Thanks for your help.
LS1429