我试图找出现在和未来时间的差异。
#include <time.h>
#include <stdio.h>
#include <float.h>
void main() {
time_t future = 0xFFFFFFFFFFF;
time_t now_time = time(NULL);
printf("The future time is %s\n", ctime(&future));
long double diff_in_sec = difftime(time(&future), time(&now_time));
printf("The diff in sec from now to future is %ld\n", diff_in_sec);
}
现在正如我所见,difftime
返回double
,即使我尝试使用long double
,我也无法在几秒钟内返回正确的时间差异。我怎样才能做到这一点?
offcourse long double
在那里没有任何意义。但我只想知道是否有另一种方法可以实现如此大的差异。
注意:我使用的是64位系统
答案 0 :(得分:1)
time_t不足以容纳0xFFFFFFFFFFF。
试试这个:
printf("%0lli\n%0lli\n", future, 0xFFFFFFFFFFF);
它会返回:
-1
4294971391
答案 1 :(得分:0)
问题在于time(&future)
调用修改future
。 difftime()
接受我机器上的原始future
值:
/** $ make CC="gcc -std=c99" kingsdeb && ./kingsdeb */
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int
main(void) {
struct tm t = {
.tm_year=559444 - 1900, .tm_mon=2, .tm_mday=8,
.tm_hour=13, .tm_min=40, .tm_sec=15, .tm_isdst=-1
};
time_t future = mktime(&t);
if (future == (time_t) -1) {
fprintf(stderr, "error: mktime returns -1 for %s", asctime(&t));
exit(EXIT_FAILURE);
}
time_t now_time = time(NULL);
if (now_time == (time_t) -1) {
perror("time");
exit(EXIT_FAILURE);
}
time_t now_from_future = future;
if (time(&now_from_future) == (time_t) -1) {
perror("time(&now_from_future)");
exit(EXIT_FAILURE);
}
double diff_in_sec = difftime(future, now_time);
if (diff_in_sec < 1 && future != now_time) {
fprintf(stderr, "difftime() returned value %f is too small\nfor "
"the time difference between (\n%s",
diff_in_sec, ctime(&future));
fprintf(stderr, "and\n%s)\n", ctime(&now_time));
exit(EXIT_FAILURE);
}
printf("The current time is %s", ctime(&now_time));
printf("time(&future) %s", ctime(&now_from_future));
printf("The future time is %s", ctime(&future));
printf("The diff in sec from now to future is %f\n", diff_in_sec);
return 0;
}
The current time is Mon Sep 8 13:52:00 2014
time(&future) Mon Sep 8 13:52:00 2014
The future time is Fri Mar 8 13:40:15 559444
The diff in sec from now to future is 17590775874495.000000
输出显示time(&ts)
将当前时间存储到ts
。不要将future
传递给它。