计算从午夜算起的毫秒数
我需要计算从午夜开始的毫秒数,编写了代码,但似乎有任何问题。
time_t t;
time_t rawtime;
char buff[256] ={0};
struct timeval tv;
struct timezone tz;
struct tm *tma;
gettimeofday(&tv, &tz);
tma=localtime(&tv.tv_sec);
static char* months[] = {"JAN", "FEB", "MAR", "APR", "MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"};
sprintf(buff,"%02d %s %d 00:00:00",tma->tm_mday, months[tma->tm_mon], tma->tm_year + 1900);
struct tm tm1;
strptime(buff, "%d %b %Y %H:%M:%S", &tm1);
tm1.tm_isdst = -1;
t = mktime(&tm1);
time ( &rawtime );
time_t milSecFromMidNight = (rawtime - t)*1000 + tv.tv_usec/1000;
似乎有些时间存在毫秒级的差异。有谁能指点一下吗?
I need to calculate the milliseconds from the mid night, written the code but seems there is any problem.
time_t t;
time_t rawtime;
char buff[256] ={0};
struct timeval tv;
struct timezone tz;
struct tm *tma;
gettimeofday(&tv, &tz);
tma=localtime(&tv.tv_sec);
static char* months[] = {"JAN", "FEB", "MAR", "APR", "MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"};
sprintf(buff,"%02d %s %d 00:00:00",tma->tm_mday, months[tma->tm_mon], tma->tm_year + 1900);
struct tm tm1;
strptime(buff, "%d %b %Y %H:%M:%S", &tm1);
tm1.tm_isdst = -1;
t = mktime(&tm1);
time ( &rawtime );
time_t milSecFromMidNight = (rawtime - t)*1000 + tv.tv_usec/1000;
It seems some time there is differences in milliseconds. Anyone can point out it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要正确计算前一个午夜(即当天开始的午夜)(作为 time_t)。你可以这样做:
重要的一点是,在将当前时间的 tm_hour、tm_min 和 tm_sec 设置为零后,你必须使用 mktime( ) 来查找午夜。
当你找到午夜的 time_t 后你就知道该做什么了。
You need to correctly calculate, as a time_t, the last previous midnight, that is, the midnight at which the current day began. You can do it something like this:
The important point is you have to use mktime( ) to find midnight after setting tm_hour, tm_min, and tm_sec of the current time to zero.
You know what to do after you find the time_t of midnight.