以毫秒为单位获取日期和时间

时间:2016-08-30 14:22:36

标签: c linux datetime

我想创建一个用当前日期和时间填充结构的函数,例如:

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

我知道我可以使用来自localtime()的{​​{1}},但问题是它只给我几秒钟的时间,我想以毫秒的分辨率得到它。我知道我也可以使用time.h,但是如何将这些结合起来以填充上面的结构?或者也许是其他提供毫秒分辨率的函数?

我怎样才能做到这一点?

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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

您可以localtimetime_t对象作为struct timeval的一部分返回gettimeofday来提供int gettimeofday(struct timeval *tv, struct timezone *tz); struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */ };

{{1}}
相关问题