计算从午夜算起的毫秒数

发布于 2024-12-11 13:49:00 字数 677 浏览 0 评论 0原文

我需要计算从午夜开始的毫秒数,编写了代码,但似乎有任何问题。

 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无所的.畏惧 2024-12-18 13:49:00

您需要正确计算前一个午夜(即当天开始的午夜)(作为 time_t)。你可以这样做:

// function to calculate midnite last night

time_t  // calc current day 00:00:00
today_at_0000 ( ) {
  time_t curtime, midtime;
  struct tm *localtm_p;
  curtime = time( NULL );
  localtm_p = localtime( &curtime );
  localtm_p->tm_hour = 0;
  localtm_p->tm_min = 0;
  localtm_p->tm_sec = 0;
  midtime = mktime( localtm_p ); // today at 00:00:00
  return midtime;
}

重要的一点是,在将当前时间的 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:

// function to calculate midnite last night

time_t  // calc current day 00:00:00
today_at_0000 ( ) {
  time_t curtime, midtime;
  struct tm *localtm_p;
  curtime = time( NULL );
  localtm_p = localtime( &curtime );
  localtm_p->tm_hour = 0;
  localtm_p->tm_min = 0;
  localtm_p->tm_sec = 0;
  midtime = mktime( localtm_p ); // today at 00:00:00
  return midtime;
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文