How do I get milliseconds since midnight UTC in C?

亡梦爱人 提交于 2019-12-29 06:59:09

问题


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


回答1:


This is a simple way:

time_t seconds_since_midnight = time(NULL) % 86400;

To get approximate milliseconds since midnight, multiply seconds_since_midnight by 1000.

If you need more resolution (consider whether you really do), you will have to use another function such as gettimeofday().




回答2:


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.




回答3:


You use gettimeofday(2) which is defined in POSIX.1 and BSD.

It returns seconds and microseconds as defined in struct timeval from sys/time.h.




回答4:


You will find C code examples for getting time and converting it to various formats here.




回答5:


Take a look at gmtime() Converts directly to Coordinated Universal Time (UTC)...



来源:https://stackoverflow.com/questions/1072455/how-do-i-get-milliseconds-since-midnight-utc-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!