0

In the case of 2/1/2016 - 1/31/2019:
I would like to output: '3 years' since the date range is 3 years.

In the case of 2/1/2016 - 3/31/2019:
I would like to output: '3 years and 2 months' since the date range is 3 years and 2 months.

I don't need to worry about days so I can just round up if that is the norm.

Are there any c# helpers out there that can help me with something like this?

Blake Rivell
  • 13,105
  • 31
  • 115
  • 231
  • Here is what you need - http://stackoverflow.com/a/4127396/4383585 – Red Apr 20 '16 at 13:20
  • 1
    The problem with this is that a year and a month are not set units of time. – juharr Apr 20 '16 at 13:20
  • @juharr While that's true, I think a naive 'months / 12 + remainder' is robust enough to display in a UI (which appears to be the goal of this) – Rob Apr 20 '16 at 13:26
  • 1
    @Rob, but how are you getting months? With days / 30? I'm not saying it isn't possible to get it's just that most solutions are going to have edge cases that won't always work how you might think they should. – juharr Apr 20 '16 at 13:29
  • @juharr Yeah, you're right - It slipped my mind that there's no `TimeSpan.TotalMonths` - in which case I agree, it does get difficult provide a robust solution – Rob Apr 20 '16 at 13:30

2 Answers2

1

For approximately calculating years and months, you can do the following :

DateTime dayStart;
DateTime dateEnd;

TimeSpan ts = dateEnt - dateStart
int years = ts.Days / 365;
int months = (ts.Days % 365) / 31;

For exact calulations , it can be tricky considering the leap years, different number of days in months,etc.

1

You could use this which doesn't really care about leap years:

DateTime first = new DateTime(2016, 2, 1);
DateTime second = new DateTime(2019, 3, 31);
double totalMonths = (second - first).TotalDays / (365.25 / 12);
int years = (int)totalMonths / 12;
int months = (int)Math.Round(totalMonths - (years * 12), 0);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • So are you saying if the date range includes a leap year the results of this would be inaccurate? Can't I just replace 365.25 with 366 if leap year? – Blake Rivell Apr 20 '16 at 13:50
  • Do most not worry about leap year since it is rare that it would actually effect the description I am trying to create? – Blake Rivell Apr 20 '16 at 13:57