例如我可以通过查看它们来计算这两个日期的差异,但是当涉及到在程序中计算这些时,我不知道。在几个小时内找出两个日期之间的差异?
日期:A是2014/02/12(y/m/d) 13:26:33
和B是2014/02/14(y/m/d) 11:35:06
然后以小时差为46
例如我可以通过查看它们来计算这两个日期的差异,但是当涉及到在程序中计算这些时,我不知道。在几个小时内找出两个日期之间的差异?
日期:A是2014/02/12(y/m/d) 13:26:33
和B是2014/02/14(y/m/d) 11:35:06
然后以小时差为46
您可以使用difftime()在C
两个时间之间计算差。但它使用mktime
和tm
。
double difftime(time_t time1, time_t time0);
一件容易的(更不用谈时区)的方法是,因为1/1/1970到两个日期(日期时间)转换为secounds。在建3600
mktime(差别和(田田)devide)应该做的工作,如果我remeber正确
HTH
我假设你的存储时间为字符串:为"2014/02/12 13:26:33"
要计算时间差,您需要使用:double difftime(time_t time_end, time_t time_beg);
函数difftime()
计算两个日历时间之间的差值为time_t
对象(time_end - time_beg
)以秒为单位。如果time_end
指的是time_beg
之前的时间点,则结果为负值。现在的问题是difftime()
不接受字符串。我们可以字符串转换成分两步time.h
定义为我也在我的答案描述time_t
结构:How to compare two time stamp in format “Month Date hh:mm:ss”:
使用char *strptime(const char *buf, const char *format, struct tm *tm);
到char*
时间字符串转换为struct tm
。
strptime()
函数使用格式指定的格式将buf指向的字符串转换为存储在tm指向的tm结构中的值。要使用它,你必须使用指定的文档格式字符串:
您的时间格式我解释格式字符串:
所以函数调用将如下:
// Y M D H M S
strptime("2014/02/12 13:26:33", "%Y/%m/%d %T", &tmi)
凡tmi
是struct tm
结构。
下面是我写的代码(阅读评论):
#define _GNU_SOURCE //to remove warning: implicit declaration of ‘strptime’
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void){
char* time1 = "2014/02/12 13:26:33"; // end
char* time2 = "2014/02/14 11:35:06"; // beg
struct tm tm1, tm2; // intermediate datastructes
time_t t1, t2; // used in difftime
//(1) convert `String to tm`: (note: %T same as %H:%M:%S)
if(strptime(time1, "%Y/%m/%d %T", &tm1) == NULL)
printf("\nstrptime failed-1\n");
if(strptime(time2, "%Y/%m/%d %T", &tm2) == NULL)
printf("\nstrptime failed-2\n");
//(2) convert `tm to time_t`:
t1 = mktime(&tm1);
t2 = mktime(&tm2);
//(3) Convert Seconds into hours
double hours = difftime(t2, t1)/60/60;
printf("%lf\n", hours);
// printf("%d\n", (int)hours); // to display 46
return EXIT_SUCCESS;
}
编译并运行:
$ gcc -Wall time_diff.c
$ ./a.out
46.142500
是你得到这样的输入作为一个字符串? – Linuxios
[你有什么尝试?](http://stackoverflow.com/help/mcve) –
你检查过这个问题吗? http://stackoverflow.com/questions/13932909/difference-between-two-dates-in-c – stamanuel