How do I get milliseconds since midnight UTC in C?

后端 未结 5 1337
太阳男子
太阳男子 2020-12-18 01:45

The time function in time.h gives milliseconds since the epoch.

5条回答
  •  执念已碎
    2020-12-18 02:32

    This is the precise way:

    struct timeval tv;
    int msec = -1;
    if (gettimeofday(&tv, NULL) == 0)
    {
        msec = ((tv.tv_sec % 86400) * 1000 + tv.tv_usec / 1000);
    }
    

    That will store into msec the number of milliseconds since midnight. (Or -1 if there was an error getting the time.)

    Although it's usually a bad idea to store time-values in an int, I'm being a little cavalier and assuming int is at least 32-bit, and can easily accommodate the range (-1) to 86,400,000.

    But I don't know if it's worth all the effort.

提交回复
热议问题