Search code examples
cepoch

Pass settimeofday() epoch time?


Is it possible to pass settimeofday() my time_t/epoch time value, in C? Could someone give me an example of how I could do it ... my C skills are a little rusty :S

Would it be:

time_t time = somevalue;
settimeofday(somevalue, NULL);

I don't have admin access where I'm working and so can't test it out.

Thanks in advance!


Solution

  • settimeofday() takes a struct timeval * as first argument, so you should do

    struct timeval tv;
    
    tv.tv_sec = somevalue;
    tv.tv_usec = 0;
    
    settimeofday(&tv,NULL);
    

    followup edit gettimeofday() is the counterpart:

    struct timeval tv;
    
    if ( !gettimeofday(&tv,NULL) ) // *always* check return values ;-)
    {
        long long microsince1970;
        microsince1970 = tv.tv_sec*1000000 + tv.tv_usec;
        printf("it's been %lld µs ago\n",microsince1970);
    }