2016-08-30 123 views
2

我想創建一個函數,將填補一個結構與當前的日期和時間,如:獲取毫秒日期和時間

typedef struct DateAndTime 
{ 
    int year; 
    int month; 
    int day; 
    int hour; 
    int minutes; 
    int seconds; 
    int msec; 
}DateAndTime; 

我知道我可以使用localtime()time.h,但問題在於它只給我幾秒鐘的時間,而我也想以毫秒爲單位解析它。我知道我可能也可以使用gettimeofday()這個,但我怎麼能結合那些得到上述結構填充?或者也許其他函數可以提供毫秒級的分辨率?

我該如何做到這一點?

注:我的系統是基於Linux的。

回答

3

您可以簡單地使用gettimeofday()獲得秒和微秒,然後用秒來調用localtime() 。你可以隨意填寫你的結構。

行此

#include <sys/time.h> 
#include <time.h> 
#include <stdio.h> 

typedef struct DateAndTime { 
    int year; 
    int month; 
    int day; 
    int hour; 
    int minutes; 
    int seconds; 
    int msec; 
} DateAndTime; 

int 
main(void) 
{ 
    DateAndTime date_and_time; 
    struct timeval tv; 
    struct tm *tm; 

    gettimeofday(&tv, NULL); 

    tm = localtime(&tv.tv_sec); 

    // Add 1900 to get the right year value 
    // read the manual page for localtime() 
    date_and_time.year = tm->tm_year + 1900; 
    // Months are 0 based in struct tm 
    date_and_time.month = tm->tm_mon + 1; 
    date_and_time.day = tm->tm_mday; 
    date_and_time.hour = tm->tm_hour; 
    date_and_time.minutes = tm->tm_min; 
    date_and_time.seconds = tm->tm_sec; 
    date_and_time.msec = (int) (tv.tv_usec/1000); 

    fprintf(stdout, "%02d:%02d:%02d.%03d %02d-%02d-%04d\n", 
     date_and_time.hour, 
     date_and_time.minutes, 
     date_and_time.seconds, 
     date_and_time.msec, 
     date_and_time.day, 
     date_and_time.month, 
     date_and_time.year 
    ); 
    return 0; 
} 
+0

簡單,因爲它可以。感謝您的解決方案和代碼! –

+1

使用'。%03d',否則1毫秒將以'.1'輸出。 – chux

+2

Pedantic:''gettimeofday()'_usually_在帶有16位int的系統上找不到,'.tv_usec'類型爲'suseconds_t'(有符號整數類型,能夠存儲至少在[-1,1000000 ]。)IAC,建議在分割後投射到'int'。 'date_and_time.msec =(int)(tv.tv_usec/1000;)'來處理16位'int'。無論如何。 – chux

1

可以喂localtimetime_t對象返回由gettimeofdaystruct timeval一部分:

int gettimeofday(struct timeval *tv, struct timezone *tz); 

struct timeval { 
    time_t  tv_sec;  /* seconds */ 
    suseconds_t tv_usec; /* microseconds */ 
};