0

Possible Duplicates:
How to get difference between two dates in Year/Month/Week/Day?
Difference in months between two dates (C#, .NET)

Hi I'm a novice at c# and I need to find out the age of a vehicle in months when I enter a date of registration. I wondered if anyone could point me in the right direction. Thanks

Community
  • 1
  • 1
Waynelee3d
  • 33
  • 5
  • It is ambiguous, the number of days in a month isn't fixed. You will also have to tell us what should happen when the vehicle was purchased on Feb 29th of a leap year. – Hans Passant May 01 '11 at 17:49
  • As above, If the vehicle was purchased on Feb 29th, on the 1st of march it would be considered 1 mth old. I just need to count the months that have elapsed since it was first registered. If the date has entered, say january the 1st, then January will be counted as 1 month. – Waynelee3d May 01 '11 at 22:24

4 Answers4

2

See > Difference in months between two dates

This is even better > How to get difference between two dates in Year/Month/Week/Day?

Community
  • 1
  • 1
neebz
  • 11,465
  • 7
  • 47
  • 64
2

It's easy to get the days, but how mamy months that is is up for discussion.

The following code uses the average 30.4 (365/12) days/month .

TimeSpan age = DateTime.ToDay - RegistrationDate;

double months1 = age.TotalDays / 30.4;

int months = (int) months1;

But some business systems will have their own rules, maybe from 2011-04-30 to 2011-05-01 will count as 1 month. You need a good definition.

H H
  • 263,252
  • 30
  • 330
  • 514
1

A very crude way of doing it would be, simply subtracting the registration date from the current time, and get the total months from the number of days:

TimeSpan age = DateTime.Now - registrationDate;
int months = (int) (age.TotalDays/30);

After a few years (about six or seven) you'll get extra months counted. Counting in months is not easy because a month is not an exact quantity. I'm guessing that a vehicle being six years old is probably very common, so this may not be a good fit.

A better alternative would be to subtract the years and the months directly:

int fullYears = (now.Year - registrationDate.Year) * 12;
int partialYear = now.Month - registrationDate.Month;
int months = fullYears + partialYear;
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
0

You can check (DateTime.Now - registrationDate).TotalDays / 31 (or 30, depending on how you define months)

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964