【问题标题】:How to compute number of seconds since the beginning of this day?如何计算从今天开始的秒数?
【发布时间】:2010-03-06 13:54:40
【问题描述】:

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

这是我的第一个猜测:

  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++ time


    【解决方案1】:

    您可以使用标准 C API:

    1. 通过time() 获取当前时间。
    2. 使用gmtime_r() 或localtime_r() 将其转换为struct tm。
    3. 将其tm_sec、tm_min、tm_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;
    }
    

    【讨论】:

      【解决方案2】:

      还可以对一天中的秒数取模:

       return nbOfSecondsSince1970 % (24 * 60 * 60)
      

      【讨论】:

        【解决方案3】:

        这是另一种可能的解决方案:

        time_t stamp=time(NULL);
        struct tm* diferencia=localtime(&stamp);
        cout << ((diferencia->tm_hour*3600)+(diferencia->tm_min*60)+(diferencia->tm_sec));
        

        【讨论】:

          【解决方案4】:

          即使在 11 年后,也有一些改进:

          • 改进了DST 处理

          • 错误检查

          • 正确的time_t减法

          代码:

          #include <ctime>
          
          // Error: return -1
          // Success: return [0 ... 90,000) (not 86,400 due to DST)
          double seconds_since_local_midnight() {
            time_t now;
            if (time(&now) == -1) {
              return -1;
            }
            struct tm timestamp;
            if (localtime_r(&now, &timestamp) == 0) { // C23
              return -1;
            }
            timestamp.tm_isdst = -1; // Important
            timestamp.tm_hour = 0;
            timestamp.tm_min = 0;
            timestamp.tm_sec = 0;
            time_t midnight = mktime(&timestamp);
            if (midnight == -1) {
              return -1;
            }
            return difftime(now, midnight);
          }
          

          其他答案的失败:

          【讨论】:

            猜你喜欢
            • 2020-12-01
            • 2016-09-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-08-11
            • 1970-01-01
            相关资源
            最近更新 更多