2010-03-06 47 views
4

我想知道自午夜以来的秒数。如何计算从今天开始以来的秒数?

这是我第一次的猜测:

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); 

回答

10

您可以使用标准的C API:

  1. 获取当前时间time()
  2. 将其转换为struct tmgmtime_r()localtime_r()
  3. 将其tm_sec,tm_min,tm_hour设置为零。
  4. 将其转换回time_tmktime()
  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) 
1

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

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

我认为更简单,我试过上面的解决方案,它不适用于VS200 8。

对话:对不起,我的英语。

编辑:这将输出始终是相同的数字,因为它只是乘以小时数 - 所以,如果它是2:00 AM将一直输出7200使用,而不是这样的:

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