开发者

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 timespa开发者_JAVA百科n 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


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!)


Here is a little snippet of code that might help

    var start = new DateTime(2009, 10, 12);
    var end = new DateTime(2014, 12, 25);

    var s = from j in Enumerable.Range(start.Year, end.Year + 1 - start.Year)
            let _start = start.Year == j ? start : new DateTime(j, 1, 1)
            let _end = end.Year == j ? end : new DateTime(j, 12, 31)
            select new { 
                year = j,
                days = Convert.ToInt32((_end - _start).TotalDays) + 1                    
            };


If I understood your problem correctly, solving it using Inclusion Exclusion principle would be the best.

Say, if your start date is somewhere in 2008 and the end date is in 2010:

NDAYS(start, end) * coeff_2008  
- NDAYS(2009, end) * coeff_2008 + NDAYS(2009, end) * coeff_2009 
- NDAYS(2010, end) * coeff_2009 + NDAYS(2010, end) * coeff_2010

Where Ndays computes the number of dates in the interval (TotalDays plus one day).

There is no need to handle leap years specially or compute december 31st. The details you can work out in a for-loop going over jan first of each year in the span.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜