current time with ctime

G

Gary Wessle

Hi

I am not getting current time with this program, what am I doing
wrong?

#include <ctime>
#include <iostream>
using namespace std;

#define P(x) cout << #x " = " << (x) << "\n";

int main(){
time_t rawtime;
P( rawtime );
P( ctime(& rawtime) );
}

**************** output ****************
rawtime = 0
ctime(& rawtime) = Thu Jan 1 10:00:00 1970
 
R

Rolf Magnus

Gary said:
Hi

I am not getting current time with this program, what am I doing
wrong?

#include <ctime>
#include <iostream>
using namespace std;

#define P(x) cout << #x " = " << (x) << "\n";

int main(){
time_t rawtime;
P( rawtime );
P( ctime(& rawtime) );
}

**************** output ****************
rawtime = 0
ctime(& rawtime) = Thu Jan 1 10:00:00 1970

Why did you expect the current time from this? ctime gives you a string
describing the point in time you give it as argument. This argument must
contain the number of seconds elapsed since 00:00:00 UTC on January 1,
1970. Since your 'rawtime' is zero, that's the time you get.
If you want to get the current time, you first have to initialize your
time_t value to that.
 
G

Gary Wessle

Rolf Magnus said:
Why did you expect the current time from this?
because off
****************************************************************
http://www.cplusplus.com/ref/ctime/ctime.html
Example.

/* ctime example */
#include <stdio.h>
#include <time.h>

int main ()
{
time_t rawtime;

time ( &rawtime );
printf ( "Current date and time are: %s", ctime (&rawtime) );

return 0;
}
****************************************************************
ctime gives you a string
describing the point in time you give it as argument. This argument must
contain the number of seconds elapsed since 00:00:00 UTC on January 1,
1970. Since your 'rawtime' is zero, that's the time you get.
If you want to get the current time, you first have to initialize your
time_t value to that.

is there a good link out there?
 
D

Default User

Rolf Magnus wrote:

Why did you expect the current time from this? ctime gives you a
string describing the point in time you give it as argument. This
argument must contain the number of seconds elapsed since 00:00:00
UTC on January 1, 1970.


That's not accurate. The form of the return from time() is not
specified, nor indeed is the type of time_t. A common implementation is
as you describe.




Brian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top