Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeSpan for different years subtracted from a bigger TimeSpan

The language I am using is C#.

I have the folowing dillema.

DateTime A, DateTime B. If A < B then I have to calculate the number of days per year in that timespan and multiply it by a coeficient that corresponds to that year. My problem is the fact that it can span multiple years.

For example:

Nr of Days in TimeSpan for 2009 * coef for 2009 + Nr of Days in TimeSpan for 2010 * coef for 2010 + etc

like image 611
Dragos Durlut Avatar asked Dec 21 '22 18:12

Dragos Durlut


1 Answers

You can't do this with a simple TimeSpan, basically. It doesn't know anything about when the span covers - it's just a number of ticks, really.

It sounds to me like there are two cases you need to consider:

  • A and B are in the same year. This is easy - just subtract one from the other and get the number of days from that
  • A and B are in different years. There are now either two or three cases:
    • The number of days after A in A's year. You can work this out by constructing January 1st in the following year, then subtracting A
    • The number of days in each year completely between A and B (so if A is in 2008 and B is in 2011, this would be 2009 and 2010)
    • The number of days in B's year. You can work this out by constructing December 31st in the previous year, then subtracting B. (Or possibly January 1st in B's year, depending on whether you want to count the day B is on or not.)

You can use DateTime.IsLeapYear to determine whether any particular year has 365 or 366 days in it. (I assume you're only using a Gregorian calendar, btw. All of this changes if not!)

like image 60
Jon Skeet Avatar answered Jan 23 '23 05:01

Jon Skeet