tags:

views:

1105

answers:

2

How would I calculate a time period between 2 dates using C (any library, etc.). For example the program would take two (local) dates and would spit out the period duration between them. For example startDate = oct-9-1976 and endDate = oct-9-2008 would show a duration of 32 years OR startDate = oct-9-1976 and endDate = dec-9-2008 would show a duration of 32 years 2 months?

Thanks.

+1  A: 

I did something very similar recently using Boost.Date_Time, and presenting the resulting function as C, but this of course requires using the C++ linker.

Actually, the example leaves a little to be desired - will the start and end dates always be on the same day of the month? If so you can ignore the day number end up with a trivial subtraction of the month and year numbers.

However if your dates can be anywhere in the month it might be a bit more tricky. Remember that not all months have the same number of days!

C difftime doesn't help you with month calculations, which is why I used Boost, though you may not have that option.

therefromhere
+3  A: 

Convert the dates into two struct tm structures with strptime

Difftime gives you the difference between the two in seconds.

Convert that into months etc with the code here (in C++, but the only C++ is for the string formatting, easy to change)

EDIT: as a commentor observed, that avoids the month issue. There is (GPL'd) code for isodiff_from_secs that can be converted to do what you want, if you're happy with its assumption that months have 30 days. See Google codesearch and the description of the standard here

Doing the fully-correct solution which takes acccount of the true months between the actual days would be pretty complex. Is that required for your problem?

Paul
therefromhere
True. Updated with another link
Paul
I was just curious to see the C version, with the assumption of the correct number of days in the months, etc. I did this thing in Groovy/Java using an excellent Joda time API: http://joda-time.sourceforge.net/Here's the Groovy/Java code: http://gist.github.com/29050
Dmitriy Kopylenko
I agree with the method. But do note that strptime will work only if the input format is stricly defined. If you want to access more input formats, check the code of GNU date (in GNU coreutils, http://www.gnu.org/software/coreutils/). You will find a lot of ideas.
bortzmeyer