In my application, a user enters two dates. A scheduled start date, and a scheduled end date. We have to take those dates, and populate 4 fields, based on the difference.
So, lets say he selects 1st Jan, 2010 as a start, and 2nd of March, 2011 as the end, we need to end up with:
Years: 1
Months: 2
Weeks: 0
Days 1
Meaning the total duration is 1 year, 2 months and 1 day.
Is there a standard way of doing this? Or would I need to write a method that has a lot of pretty tricky logic to work it out? I was hoping I’d be lucky, and there would be a date-diff type .Net class available.
Heres a complete method, weeks are not included, but could be added relatively simply. It’s a somewhat complex question (asked in a multitude of ways on stackoverflow and answered poorly in a multitude of ways), but none the less can be answered. The TimeSpan object gives us part of what we need, but only works up through days. I’ve written a significant number of tests against this method, if you find a hole, please post a comment.
What this will do is compare 2 dates, getting the years, months, days, hours, and minutes. (e.g. some event happened 1 year, 6 months, 3 days, 4 hours and 7 minutes ago)
Because this question has been asked and attempted to be answered so many times, I’m not sure this will ever even get noticed, but if so it should provide value.