Find the answer to your Linux question:
Results 1 to 3 of 3
Hello I presently have an int field representing the epoch seconds. I need to convert this into "2008/03/17 11:46:00". Can someone tell me how to do this please. I am ...
  1. #1
    Just Joined!
    Join Date
    Jan 2008
    Posts
    22

    Converting Epoch to readable date/time in C

    Hello
    I presently have an int field representing the epoch seconds. I need to convert this into "2008/03/17 11:46:00". Can someone tell me how to do this please.

    I am trying to use strftime, but it spits out incorrect values, im not sure why, maybe because its an int and not a time_t.

    This is what I am doing now ..

    Code:
    char *format_datetime(time_t time_ptr)
    {
        #ifdef LINUX
            /* convert from network endian to little endian */
            time_ptr = ntohs(time_ptr);
        #endif
    
        static char buf[30];
        strftime(buf,30 , "%Y%m%d %H:%M:%S",localtime(&time_ptr));
    
        return buf;
    }
    
    printf("%s",format_datetime(&integer_time_in_epochSec);
    thanks

  2. #2
    Linux Newbie
    Join Date
    Jan 2008
    Location
    UK
    Posts
    211
    Here is an example and its output * strftime example */
    #include <stdio.h>
    #include <time.h>

    int main ()
    {
    time_t rawtime;
    struct tm * timeinfo;
    char buffer [80];

    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    strftime (buffer,80,"Now is &#37;I:%M%p.",timeinfo);
    puts (buffer);

    return 0;
    }

    Example output:


    Now is 03:21PM.

    As you can see it uses time_t.

    Hope this may help.

  3. #3
    Just Joined!
    Join Date
    Jan 2008
    Posts
    22
    Turns out I was doing an extra ntohs in the code there and hence the time was coming out all messed up. Fixed that, everything seems ok now.

    Thanks a lot for your help.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...