c++ - 如何计算自今天开始以来的秒数?

标签 c++ time

我想获取自午夜以来的秒数。

这是我的第一个猜测:

  time_t current;
  time(&current);
  struct tm dateDetails;
  ACE_OS::localtime_r(&current, &dateDetails);

  // Get the current session start time
  const time_t yearToTime     = dateDetails.tm_year - 70; // year to 1900 converted into year to 1970
  const time_t ydayToTime     = dateDetails.tm_yday;
  const time_t midnightTime   = (yearToTime * 365 * 24 * 60 * 60) + (ydayToTime* 24 * 60 * 60);
  StartTime_                  = static_cast<long>(current - midnightTime);

最佳答案

您可以使用标准 C API:

  1. 使用 time() 获取当前时间。
  2. 使用 gmtime_r()localtime_r() 将其转换为 struct tm
  3. 将其 tm_sectm_mintm_hour 设置为零。
  4. 使用 mktime() 将其转换回 time_t
  5. 找出原始 time_t 值与新值之间的差异。

例子:

#include <time.h>
#include <stdio.h>

time_t
day_seconds() {
    time_t t1, t2;
    struct tm tms;
    time(&t1);
    localtime_r(&t1, &tms);
    tms.tm_hour = 0;
    tms.tm_min = 0;
    tms.tm_sec = 0;
    t2 = mktime(&tms);
    return t1 - t2;
}

int
main() {
    printf("seconds since the beginning of the day: %lu\n", day_seconds());
    return 0;
}

关于c++ - 如何计算自今天开始以来的秒数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2392660/

相关文章:

c++ - 通过 std::thread 以 std::function 作为参数调用可调用对象

c++ - 运算符(operator)重载功能不起作用

c++ - 删除 char** 数组的正确方法

python - python跨平台高精度时间

sql - 如何在两列时间类型之间获取时间?

C++:如何使用时间和本地时间获取实际时间?

戈朗 : convert milliseconds to time

c++ - 如何概括普通二维数组?

excel - ……:mm:ss format causing IF statement to return False

c++ - 模块 ilink32.dll 中的访问冲突