0

I would like to print the current time and the time of 10 minutes ago, but I don't know how to generate a time_t of X minutes ago...

#include <time.h>

time_t current_time;
time_t tenMinutesAgo;

current_time = time(NULL);
tenMinutesAgo = ???;

printf("current time = %s, 10 minutes ago = %s\n",ctime(current_time),ctime(tenMinutesAgo));

Any help would be much appreciated!

4

2 回答 2

3

由于从纪元(通常是 Unix 纪元)time(NULL)返回以秒为单位的时间,即1970 年 1 月 1 日的00:00:00 UTC(或 1970-01-01T00:00:00Z ISO 8601)

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

time_t current_time;
time_t tenMinutesAgo;

int main() {
  char* c_time_string;
  current_time = time(NULL);
  tenMinutesAgo = current_time - 10*60;//the time 10 minutes ago is 10*60

  c_time_string = ctime(&tenMinutesAgo);//convert the time tenMinutesAgo into a string format in the local time format

  printf("The time 10 minutes ago in seconds from the epoch is: %i\n", (int)tenMinutesAgo);
  printf("The time 10 minutes ago from the epoch in the local time format is: %s\n", c_time_string);

  return 0;
}

编辑:

@PaulGriffiths 提出了一个很好的观点,即我的解决方案不能保证是可移植的。如果您想要便携性,请查看他的答案。但是,如果您在任何最流行的操作系统风格(*nix、Solaris、Windows)上编写代码,这个解决方案都可以工作。

于 2013-08-11T11:58:18.777 回答
0

第一个答案不能保证是可移植的,因为 C 标准不要求time_t以秒为单位进行测量。

time_t不过,它是一个真正的类型,所以你可以对它进行算术运算,这确实为我们提供了实现它的途径。您可以设置两个struct tmsa 秒:

struct tm first;
struct tm second;
time_t ts_first;
time_t ts_second;
double sec_diff;

first.tm_year = 100;
first.tm_mon = 0;
first.tm_mday = 2;
first.tm_hour = 1;
first.tm_minute = 20;
first.tm_second = 20;
first.tm_isdst = -1;

second.tm_year = 100;
second.tm_mon = 0;
second.tm_mday = 2;
second.tm_hour = 1;
second.tm_minute = 20;
second.tm_second = 21;
second.tm_isdst = -1;

将它们转化为time_t值:

ts_first = mktime(&first);
if ( ts_first == -1 ) {
    /* Do your error checking  */
}

ts_second = mktime(&second);
if ( ts_second == -1 ) {
    /* Do your error checking  */
}

呼吁difftime()他们:

sec_diff = difftime(ts_second, ts_first);

然后你可以乘以sec_diff你想要的秒数,然后从返回的值中减去它time

当然,如果您的可用系统时间分辨率大于一秒,这将不起作用,并且您可以尝试更改tm_min成员,因为您正在寻找分钟,但这不太可能。

于 2013-08-11T12:33:10.360 回答