c++ - 从午夜开始计算毫秒数

标签 c++ c unix unix-timestamp

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

 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;

似乎有些时间以毫秒为单位存在差异。谁能指出来?

最佳答案

您需要正确计算前一个午夜,即当天开始的午夜,作为 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 后,您就知道该怎么做了。

关于c++ - 从午夜开始计算毫秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7865941/

相关文章:

c - 指针的行为;字符 ** argv

c - 如何将 16 位数字存储在两个字节的 char 数组中?

linux - 如何在Linux终端中打印文件中最频繁的行?

unix - AWK 根据搜索模式打印特定行

c++ - 将基类 2 参数构造函数调用到子类 1 参数构造函数中

c++ - 安装了 Xcode 命令行工具的 Mac OS X 中的 clang-format 和 clang-format.py 在哪里?

c++ - 当使用从 operator new 返回的指针作为指向数组元素的指针时,这是未定义的行为吗

c++ - 使用 oracle occi 和 c++ 将 1300 万行转储到文件中

c - 为什么当我们在下面的代码中逐行读取文件时程序会崩溃?

Caesar Cipher C 程序未正确加密