获取毫秒日期和时间

问题描述:

我想创建一个函数,将填补一个结构与当前的日期和时间,如:获取毫秒日期和时间

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

我知道我可以使用localtime()time.h,但问题在于它只给我几秒钟的时间,而我也想以毫秒为单位解析它。我知道我可能也可以使用gettimeofday()这个,但我怎么能结合那些得到上述结构填充?或者也许其他函数可以提供毫秒级的分辨率?

我该如何做到这一点?

注:我的系统是基于Linux的。

您可以简单地使用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

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

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

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