For example I can calculate the difference of these two dates by looking at them but i have no clue when it comes to calculating this in a program.
Dates: A is 201
You may use difftime() to calculate difference between two times in C
. However it uses mktime
and tm
.
double difftime(time_t time1, time_t time0);
an easy (not to talk about timezones) approach is to convert both dates (datetimes) to secounds since 1/1/1970. the build the difference and (tada) devide by 3600
mktime() should do the work, if I remeber correctly
HTH
I assume your stores time as strings: as "2014/02/12 13:26:33"
To calculate time difference you need to use: double difftime( time_t time_end, time_t time_beg);
the function difftime()
computes difference between two calendar times as time_t
objects (time_end - time_beg
) in seconds. If time_end
refers to time point before time_beg
then the result is negative. Now the problem is difftime()
doesn't accepts strings. We can convert string into time_t structure defined in time.h in two steps as I also described in my answer: How to compare two time stamp in format “Month Date hh:mm:ss”:
Use char *strptime(const char *buf, const char *format, struct tm *tm); to convert char*
time string into struct tm.
The
strptime()
function converts the character string pointed to by buf to values that are stored in the tm structure pointed to by tm, using the format specified by format. To use it you have to using format string specified in documentation:
For your time format I am explaining format strings:
So function call will be as follows:
// Y M D H M S
strptime("2014/02/12 13:26:33", "%Y/%m/%d %T", &tmi)
Where tmi
is a struct tm
structure.
Step two would be to use: time_t mktime(struct tm *time);
Below is the code I have written(read comments):
#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;
}
Compile and run:
$ gcc -Wall time_diff.c
$ ./a.out
46.142500