代码之家  ›  专栏  ›  技术社区  ›  yves Baumes

如何计算从今天开始到现在的秒数?

  •  4
  • yves Baumes  · 技术社区  · 16 年前

    我想知道午夜后的秒数。

    我的第一个猜测是:

      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);
    
    3 回复  |  直到 12 年前
        1
  •  12
  •   Alex B    16 年前

    您可以使用标准C API:

    1. 获取当前时间 time()
    2. 将其转换为 struct tm 具有 gmtime_r() localtime_r()
    3. 设置其 tm_sec , tm_min , tm_hour 到零。
    4. 把它转换回 time_t 具有 mktime()
    5. 找出原作之间的区别 Timet 价值和新的。

    例子:

    #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
  •  3
  •   yves Baumes    12 年前

    一天中的秒数的模也可以:

     return nbOfSecondsSince1970 % (24 * 60 * 60)
    
        3
  •  1
  •   Juanan76    12 年前

    下面是另一个可能的解决方案:

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

    我认为更简单的是,我尝试了上面的解决方案,但在vs2008中不起作用。

    附言:对不起我的英语。

    编辑:这将始终输出相同的数字,因为它只会乘以小时数-因此,如果是凌晨2:00,将始终输出7200。请改为:

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