2013-04-23 461 views
2

將秒轉換爲日期的C程序。 我有以下的C程序代碼。使用C語言將1970年1月1日之前的秒轉換爲日期

#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語言的秒數轉換爲創建日期?

+3

你會發現你的文檔中需要:http://en.cppreference.com/w/c/chrono – Nim 2013-04-23 08:25:50

+0

看到這個答案可能幫助http://stackoverflow.com/questions/8304259/formatting-struct-timespec/14746954#14746954 – MOHAMED 2013-04-23 08:44:46

+0

st_birthtime和st_ctime的類型是timespec – MOHAMED 2013-04-23 08:46:02

回答

3

根據您的需要,標準C函數將自紀元到故障時間之間的秒數轉換爲localtime()gmtime()。然後,您可以使用asctime()將分解的時間轉換爲字符串。不要忘記#include <time.h>並閱讀相應的手冊頁。

+0

你也可以提到'strftime'來獲取打印日期的字符串版本(帶有任意本地化的'strftime_l') 。 – Will 2013-04-23 10:02:45

+0

好吧,我提到'strftime',但不是'strftime_l',它不是一個標準的C函數(我們不應該假設任何超越標準C的東西,因爲OP沒有指定任何OS或C實現)。 – Jens 2013-04-23 10:12:47

0

這裏有一些功能,我使用:

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); 
} 
相關問題