A simple example calculating the number of seconds since 01/01/1970

C

cyril

I saw that is a recurrent message but i couln't succed in founding the
solution ...

I'm developping under Linux

Does anyone have a code snippet that permit to get in a simple long
var the number of sec since 01/01/1970.... I come from the Java world
;o)

Thanks for all.

PS : the code I try give me a negative value :
tm is a tm struct
currenttime and t_70 are some time_t struct;

tm.tm_day = 1;
tm.tm_year = 1970;
t_70 = mktime(&tm); //normally initialized to 0

currenttime = time(NULL);

sec = difftime(t_70, currenttime);
 
C

Corne' Cornelius

tm.tm_year should be set to the number of years since 1900, not the
actual year you want.

so in effect, t_70 is after currenttime, which would give you a negative
value.
 
M

Martijn

cyril said:
Does anyone have a code snippet that permit to get in a simple long
var the number of sec since 01/01/1970.... I come from the Java world
;o)

time_t t = time(NULL);

Depending on your implementation, time_t may be a typedef of long. If you
_really_ need a long, go cast it.

long l = (long)t;

Good luck,
 
R

Richard Heathfield

Martijn said:
time_t t = time(NULL);

Depending on your implementation, time_t may be a typedef of long. If you
_really_ need a long, go cast it.

long l = (long)t;

Bad advice. Even if time_t is a long on his implementation, the resulting
code will not be portable. Indeed, it might not even work, since the
Standard does not require time_t to represent the number of seconds since
1/1/1970.

The OP would do better to build a struct tm like this:

struct tm firstjan1970 = {0};
firstjan1970.tm_year = 70;
firstjan1970.tm_mon = 0;
firstjan1970.tm_mday = 1;

and then call mktime to get a time_t.

The next steps are to get the current time using time(), and then call
difftime() to get the number of seconds difference as a double.
 
C

cyril

Thanks to all your advices, i succed in what I wanna do.

Thanks for all.

Regards, Cyril.
 

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

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top