TimeSpan for different years is subtracted from the larger TimeSpan

The language I use is C #.

I have the following dilemma.

DateTime A, DateTime B. If A <B then I have to calculate the number of days in a year in this period of time and multiply it by a coefficient corresponding to this year. My problem is that it can span several years.

For instance:

Nr of Days in TimeSpan for 2009 * coefficient. for 2009 + the number of days in TimeSpan for 2010 * coefficient. for 2010 + etc.

+4
source share
3 answers

Here is a small piece 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 }; 
+3
source

You cannot do this with a simple TimeSpan , basically. He knows nothing about when covers covers - these are just a few ticks, really.

It seems to me that there are two cases that you need to consider:

  • A and B are in the same year. It's easy - just subtract one from the other and get the number of days from it
  • A and B are in different years. There are currently two or three cases:
    • The number of days after A in a year. You can do this by building January 1 next year, then subtracting A
    • The number of days in each year is completely between A and B (therefore, if A is in 2008 and B is in 2011, this will be 2009 and 2010).
    • The number of days in year B. You can fix this by building December 31 in the previous year and then subtracting B. (Or maybe January 1 in year B, depending on whether you want to count day B on or not.)

You can use DateTime.IsLeapYear to determine if any particular year has 365 or 366 days. (I assume that you only use the Gregorian calendar, by the way, all this changes, if not!)

+6
source

If I understood your problem correctly, it could be solved using the principle of exclusion of inclusion .

Let's 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 calculates the number of dates in an interval (TotalDays plus one day).

There is no need to handle leap years on purpose or calculate December 31. Details that you can develop in a cycle passing through jan first of each year in the interval.

+2
source

Source: https://habr.com/ru/post/1338991/


All Articles