Calculate time period using C

How do I calculate the time period between two dates in C (any library, etc.)?

The program should take two (local) dates as input and provide a period of duration between them as output.

For example,

startDate = OCT-09-1976 and endDate = OCT-09-2008 
should show a duration of 32 years. 

startDate = OCT-09-1976 and endDate = DEC-09-2008 
should show a duration of 32 years and 2 months.

      

Thank.

0


source to share


2 answers


Convert dates to two tm structs with strptime

Difftime gives the difference between two seconds.

Convert that to months, etc. with code here (in C ++, but the only C ++ for string formatting, easily changeable)



EDIT: As the commenter pointed out, that avoids the question of the month. There is (GPL'd) code for isodiff_from_secs that can be converted to do what you want, if you're happy with your assumption that months have 30 days. See google codeearch and standard description here

Doing a completely correct solution that takes into account the true months between the actual days will be quite tricky. Is this necessary for your problem?

+3


source


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

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



However, if your dates could be anywhere in the month, this can be a little tricky. Remember, not all months have the same number of days!

C diffftime doesn't help you with monthly calculations, so I used Boost, although you may not have this option.

+1


source







All Articles