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

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

问题描述:

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

I would like to create a function that will fill a struct with the current date and time, such as:

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

我知道我可以使用 localtime()来自 time.h 的问题,但问题是它只给我几秒钟的时间,而我也想获得毫秒级的分辨率。我知道我也许还可以使用 gettimeofday(),但是我怎样才能将它们组合起来以填充上面的结构呢?还是可能提供毫秒级分辨率的其他功能?

I know I can use localtime() from time.h, but the problem is that it gives me only time in seconds, and I want to get it also in milliseconds resolution. I know I might be able to use also gettimeofday() for this, but how can i combine those to get the above struct filled? Or maybe other function that gives milliseconds resolution?

我该如何实现?

注意:我的系统基于linux。

Note: My system is linux based.

您可以只需使用 gettimeofday()获得秒和微秒,然后使用秒调用 localtime()。然后,您可以根据需要填充您的结构。

You could simply use gettimeofday() to obtain the seconds and micro seconds, and then use the seconds to call localtime(). You then can fill your structure as you wish.

为此行

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