Anusha
Anusha

Reputation: 95

Convert seconds from Jan 1st 1970 to date using C language

C program to convert seconds to Date. I have the following C program code.

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>

#ifdef HAVE_ST_BIRTHTIME
#  define birthtime(x) (x).st_birthtime
#else
#  define birthtime(x) (x).st_ctime
#endif

int main(int argc, char *argv[])
{
    struct stat st;
    size_t i;

    for( i=1; i<argc; i++ )
    {
        if( stat(argv[i], &st) != 0 )
            perror(argv[i]);
        printf("%i\n", birthtime(st));
    }

    return 0;
}

It returns time in seconds from Jan 1st 1970 to the file creation date. How do I convert the seconds to date of creation using C language only?

Upvotes: 2

Views: 12222

Answers (2)

Jens
Jens

Reputation: 72629

The Standard C function to convert seconds since the epoch to a broken down time, is localtime() or gmtime(), depending on your needs. You might then use asctime() to convert broken down times to a string. Don't forget to #include <time.h> and read the corresponding manual pages.

Upvotes: 4

Dariusz
Dariusz

Reputation: 22241

Here are some functions I use:

typedef int64_t timestamp_t;

timestamp_t currentTimestamp( void )
{
  struct timeval tv;
  struct timezone tz;
  timestamp_t timestamp = 0;
  struct tm when;
  timestamp_t localeOffset = 0;

  { // add localtime to UTC
    localtime_r ( (time_t*)&timestamp, &when);
    localeOffset = when.tm_gmtoff * 1000;
  }

  gettimeofday (&tv, &tz );
  timestamp = ((timestamp_t)((tv.tv_sec) * 1000) ) + ( (timestamp_t)((tv.tv_usec) / 1000) );

  timestamp+=localeOffset;

  return timestamp;
}

/* ----------------------------------------------------------------------------- */

int32_t timestampToStructtm ( timestamp_t timestamp, struct tm* dateStruct)
{
  timestamp /= 1000; // required timestamp in seconds!
  //localtime_r ( &timestamp, dateStruct);
  gmtime_r ( &timestamp, dateStruct);

  return 0;
}

/* ----------------------------------------------------------------------------- */


int32_t sprintf_timestampAsYYYYMMDDHHMMSS ( char* buf, timestamp_t timestamp )
{
  int year = 0;
  int month = 0;
  int day = 0;
  int hour = 0;
  int minute = 0;
  int second = 0;
  struct tm timeStruct;

  if (timestamp==TIMESTAMP_NULL) {
    return sprintf(buf, "NULL_TIMESTAMP");
  }

  memset (&timeStruct, 0, sizeof (struct tm));
  timestampToStructtm(timestamp, &timeStruct);

  year = timeStruct.tm_year + 1900;
  month = timeStruct.tm_mon + 1;
  day = timeStruct.tm_mday;
  hour = timeStruct.tm_hour;
  minute = timeStruct.tm_min;
  second = timeStruct.tm_sec;

  return sprintf(buf, "%04d%02d%02d%02d%02d%02d", year, month, day, hour, minute, second);
}

Upvotes: 1

Related Questions