"Ashish Sheth" <ea*****@gmail.com> wrote in

news:#D*************@tk2msftngp13.phx.gbl:

Hi All,

In C#, How can I get the difference between two dates in number of

months? I tried to use the Substract method of the DateTime class and

it is giving me the difference in TimeSpan,From which I can get the

duration in days, hours and so.. but how can I get the difference in

months? Please reply ASAP. it's urgent.

Please explain how the difference in number of months can safely be

calculated from a TimeSpan value.

For instance, subtracting the last day of one month from the last day of

another month would for some be considered 1 month, but if the first date

was the 31st of january and the second date was the 28th of february, only

28 days have elapsed, is that a month ? How about from the 28th of february

to the 31st of march, that's 31 days. Is that one month too ? Even though

the second month there is bigger than the first ?

If you divide by 30 you get "1 year = 12 + 1/6 months". If you divide by 31

you get "1 year = 11 + 24/31 months". If you start with clever logic to

take the day of the month into account, you get months of varying sizes,

and TimeSpan has lost all references to the original dates so it can't

assume anything about the number of days it has stored.

The reason for years and months not appearing in the timespan class is

because of this problem. If you can define how to calculate the number of

months between two dates, just make a helper class that does just that.

--

Lasse Vågsæther Karlsen

http://www.vkarlsen.no/
mailto:la***@vkarlsen.no

PGP KeyID: 0x0270466B