使用C语言将1970年1月1日之后的秒数转换为日期

时间:2013-04-23 08:22:16

标签: c

将秒转换为日期的C程序。 我有以下C程序代码。

#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;
}

它返回从1970年1月1日到文件创建日期的秒数。如何仅使用C语言将创建的秒数转换为创建日期?

2 个答案:

答案 0 :(得分:3)

标准C功能可以将自纪元以来的秒数转换为细分时间,具体为localtime()gmtime(),具体取决于您的需求。然后,您可以使用asctime()将细分时间转换为字符串。不要忘记#include <time.h>并阅读相应的手册页。

答案 1 :(得分:1)

以下是我使用的一些功能:

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);
}