Split date range into several specific date range chunks - c#

I have regular list of date ranges with specific value:
14.09.2012 - 31.12.2015 = 8.25
01.01.2016 - 13.06.2016 = 11.00
14.06.2016 - 18.09.2016 = 10.50
19.09.2016 - 26.03.2017 = 10.00
27.03.2017 - 01.05.2017 = 9.75
02.05.2017 - 18.06.2017 = 9.25
19.06.2017 - 17.09.2017 = 9.00
18.09.2017 - 29.10.2017 = 8.50
30.10.2017 - 17.12.2017 = 8.25
18.12.2017 - 11.02.2018 = 7.75
12.02.2018 - 25.03.2018 = 7.50
26.03.2018 - 16.09.2018 = 7.25
17.09.2018 - NOW = 7.50
I am looking for a method that divide one input data range into above data ranges taking into account coefficient value.
For example, if I have input date range 01.01.2016 - 09.02.2016, I need to get one output date range and coefficient:
01.01.2016 - 13.06.2016 = 11.00
But if I have input date range 01.01.2016 - 29.04.2017, I need to get following ranges and coefficients:
14.09.2012 - 31.12.2015 = 8.25
01.01.2016 - 13.06.2016 = 11.00
14.06.2016 - 18.09.2016 = 10.50
19.09.2016 - 26.03.2017 = 10.00
27.03.2017 - 01.05.2017 = 9.75
Class for output data:
public class OutputItem
{
public OutputItem()
{
}
public DateTime Start { get; set; } = new DateTime();
public DateTime End { get; set; } = new DateTime();
public double Coeff { get; set; } = 0;
}
Method that I try to get output data
private List<OutputItem> GetOutput(DateTime start, DateTime end, List<OutputItem> specificRanges)
{
List<OutputItem> periods = new List<OutputItem>();
foreach (OutputItem sr in specificRanges)
{
if (start >= sr.Start && sr.End <= end)
{
periods.Add(new OutputItem { Start = sr.Start, End = sr.End, Coeff = sr.Coeff });
}
}
return periods;
}

So I'm going to go out on a limb here and assume that in your second example the start date should have been before 01-01-2016 - because if I understand the question, you are looking to return all the ranges that overlap the start to end time you are passing to the method.
If that is indeed the case, you are close - but your condition is wrong.
The way to test if two ranges overlap is to check if one starts before the other ends and vice versa, as you can see in the wiki of the overlap tag:
Two or more elements overlap when they partially or totally cover one another.
The way to find if the elements overlap or not is to test if one elements begins before the second one ends, while the second one begins before the first one ends.
So your method should be:
private List<OutputItem> GetOutput(DateTime start, DateTime end, List<OutputItem> specificRanges)
{
List<OutputItem> periods = new List<OutputItem>();
foreach (OutputItem sr in specificRanges)
{
if (start >= sr.End && sr.Start <= end)
{
periods.Add(new OutputItem { Start = sr.Start, End = sr.End, Coeff = sr.Coeff });
}
}
return periods;
}

Related

Finding the month between a range

I have a datasource that returns dates and I have to find where the months falls within the month and day range buckets. The months and day range buckets are predefined so I put it in a Dictionary (not sure if that is even a good idea). I am using linq to find the min and Max dates and extracting the month from them. I need to find month from the dictionary where that month extracted falls within the range. For Example
Dictionary<int, int> MonthDayBuckets = new Dictionary<int, int>() { { 3,31 }, { 6,30 }, { 9,30 }, { 12,31 } };
var MinyDate = _dataSource.Min(x => x.values[0]);
var MaxDate = _dataSource.Max(x => x.values[0]);
var startMonth = Convert.ToDateTime(MinyDate).ToString("MM");
var endMonth = Convert.ToDateTime(MaxDate).ToString("MM");
Say startmonth return Jan so I want to be able to go to the dictionary and return only march (03.31) and if I get 10 for the Max (October) I am trying to return (12,31) December
If my understanding is correct, your MonthDayBuckets variable is meant to represent date ranges:
3/31 - 6/30
6/30 - 9/30
9/30 - 12/31
12/31 - 3/31
...and given a month, you're wanting to see what the end date is of the interval that the first of that month falls between? Like you gave the example of October returning 12/31.
This problem can be simplified since you'll get the same result saying "what's the next occurring date after this given date?" The next occurring date for 10/01 would be 12/31. So here's how you could rearrange your data:
var availableDates = new List<string> { "03/31", "06/30", "09/30", "12/31" };
Now you'll be able to find a match by finding the index of the first one that's greater than your given date. Note how I made the month/day combos lexicographical orderable.
var startMonth = Convert.ToDateTime(MinyDate).ToString("MM");
var startDate = startMonth + "/01";
var endMonth = Convert.ToDateTime(MaxDate).ToString("MM");
var endDate = endMonth + "/01";
// Wrap around to the first date if this falls after the end
var nextStartDate = availableDates.FirstOrDefault(d => d.CompareTo(startDate) >= 1) ?? availableDates[0];
var nextEndDate = availableDates.FirstOrDefault(d => d.CompareTo(endDate) >= 1) ?? availableDates[0];
You could use Linq for the purpose. For example,
var nearestKey = MonthDayBuckets.Keys.Where(x => x >= endMonth.Month).Min();
var nearestDate = new DateTime(DateTime.Now.Year,nearestKey,MonthDayBuckets[nearestKey]); // or whatever the year it needs to be represent
Though above query would get you the result, I would suggest you define a structure to store the Range itself, rather than using Dictionary
For example,
public class Range
{
public MonthDate StartRange{get;set;}
public MonthDate EndRange{get;set;}
public Range(MonthDate startRange,MonthDate endRange)
{
StartRange = startRange;
EndRange = endRange;
}
}
public class MonthDate
{
public MonthDate(int month,int date)
{
Month = month;
Date = date;
}
public int Month{get;set;}
public int Date{get;set;}
//Depending on if your Ranges are inclusive or not,you need to decide how to compare
public static bool operator >=(MonthDate source, MonthDate comparer)
{
return source.Month>= comparer.Month && source.Date>=comparer.Date;
}
public static bool operator <=(MonthDate source, MonthDate comparer)
{
return source.Month<= comparer.Month && source.Date<=comparer.Date;
}
}
Now you could define ranges as
var dateRanges = new Range[]
{
new Range(new MonthDate(12,31),new MonthDate(3,31)),
new Range(new MonthDate(3,31),new MonthDate(6,30)),
new Range(new MonthDate(6,30),new MonthDate(12,31)),
};
var result = dateRanges.First(x=>x.StartRange <= new MonthDate(endMonth.Month,endMonth.Day) && x.EndRange >= new MonthDate(endMonth.Month,endMonth.Day));

How can I get a collection of months between two Dates?

Below is my code. I am only getting the difference between two dates, but I want the name of that month which comes between the from and to dates.
public static int GetMonthsBetween(DateTime from, DateTime to)
{
if (from > to) return GetMonthsBetween(to, from);
var monthDiff = Math.Abs((to.Year * 12 + (to.Month - 1)) - (from.Year * 12 + (from.Month - 1)));
if (from.AddMonths(monthDiff) > to || to.Day < from.Day)
{
return monthDiff - 1;
}
else
{
return monthDiff;
}
}
Based on your code you could substract the month difference from the "to" DateTime to get DateTime difference from your input.
public static List<DateTime> GetMonthsBetween(DateTime from, DateTime to)
{
if (from > to) return GetMonthsBetween(to, from);
var monthDiff = Math.Abs((to.Year * 12 + (to.Month - 1)) - (from.Year * 12 + (from.Month - 1)));
if (from.AddMonths(monthDiff) > to || to.Day < from.Day)
{
monthDiff -= 1;
}
List<DateTime> results = new List<DateTime>();
for (int i = monthDiff; i >= 1; i--)
{
results.Add(to.AddMonths(-i));
}
return results;
}
To get the name of the month just format the DateTime to "MMM".
var dts = GetMonthsBetween(DateTime.Today, DateTime.Today.AddMonths(5));
foreach (var dateTime in dts)
{
Console.WriteLine(dateTime.ToString("MMM"));
}
If you want the names of all months between two dates, use something like this:
var d1 = new DateTime(2015,6,1);
var d2 = new DateTime(2015,9,1);
var monthlist = new List<string>();
string format = d1.Year == d2.Year ? "MMMM" : "MMMM yyyy";
for (var d = d1; d <= d2; d = d.AddMonths(1))
{
monthlist.Add(d.ToString(format));
}
The full list is now in monthlist - you will want to return that from your method.
Assuming you're using Java and JodaTime there are several flaws in your code.
You cant use from > to to evaluate if a date is after an other. Use from.isAfter(to) instead.
JodaTime already supplies a method to calculate the amount of whole months between two given Dates Months.monthsBetween(start,end).
With the calculated month difference you can instantiate a new DateTime object that holds a date in your desired month and output its name via yourNewDateTimeObject.month().getAsText().
edit: Just found out you're using C# so ignore my text above this. Below here I will try to answer your question in C#.
Why dont you just subtract the from from the to date and obtain your difference?
The resulting TimeSpan can be used to determine the amount of whole months between your two given dates.
To obtain the resulting month name you could use yourDateTime.ToString("MMMM");

Grouping drop down list and applying them to a set of equations

I'm very new to using this site and to C# .Net so be gentle!
What is my project? I am creating a timesheet for my parents side business that doctors can fill out online. There are call hours and regular hours that I have created if statements for to equate the correct hours for both call and regular.
What am I trying to accomplish? I would like the user to click one submit button and have each group of drop down lists corresponding to each day run through the equations and give a total.
What is my question? How can I first off - group a set of Drop Down Lists and then - how would the code look to say something like "for some label(LabelMondayCALL.Text), use this group (DDL_In_Monday, DDL_OutBreak_Monday, etc.) of drop downs to find what the label would be."
Why do I want to do this? To avoid copy and pasting pages of code for each individual day and to try and keep things clean and simple for possible future changes.
Here is some code:
DateTime MondayDDL4 = DateTime.Parse(DDL_Out_Monday.SelectedValue);
DateTime MondayDDL3 = DateTime.Parse(DDL_InBreak_Monday.SelectedValue);
DateTime MondayDDL2 = DateTime.Parse(DDL_OutBreak_Monday.SelectedValue);
DateTime MondayDDL1 = DateTime.Parse(DDL_In_Monday.SelectedValue);
else if ((MondayDDL1 <= FromCompHours) & (MondayDDL4 <= FromCompHours)) //comp time earlier than 6:30
{
LabelMondayREG.Text = "00:00:00";//works
LabelMondayCALL.Text = MondayDDL4.Subtract(MondayDDL1).ToString();//works
if ((BreakStart != "00:00:00") & (BreakEnd != "00:00:00"))
{
LabelMondayREG.Text = "00:00:00";
String CompTimeBreakHours = (BreakEndDT.Subtract(BreakStartDT)).ToString();
LabelMondayCALL.Text = ((DateTime.Parse(LabelMondayCALL.Text)) - (DateTime.Parse(CompTimeBreakHours))).ToString();
}
}
Thanks for any help you can provide and please let me know if you see anything else that I could simplify, like I said I'm fairly new to this stuff.
Here is some more code and a picture of the actual site, but here is a little bit more of a description of what I'm doing: Basically these equations are deciding what time (Call hours or Regular Hours) the doctors break should be subtracted from, for one day of the week, from a row of drop down menus. However I would prefer not to copy this code for each set of drop down lists. So I wanted to know if there was a way to create an instance to have the call hours and regular hours labels use only the drop downs that correspond to the day they are labeled.
so MondayDDL1, 2, ,3 and 4 run through the equation and their answers fill in LabelMondayCall and LabelMondayReg
and then
TuesdayDDL1, 2, ,3 and 4 run through the equation and their answers fill in LabelTuesdayCall and LabelTuesdayReg
Never mind no image I don't have enough reputation
here is a bit of what the layout looks like though
mondayDDL1 mondayDDL2 mondayDDL3 mondayDDL4 LABELmondayREG LABELmondayCALL
tuesdayDDL1 tuesdayDDL2 tuesdayDDL3 tuesdayDDL4 LABELtuesdayREG LABELtuesdayCALL
protected void ButtonCalculate_Click(object sender, EventArgs e)
{
//DropDownList2.Items.Clear();
//DropDownList2.SelectedValue = null;
//DropDownList3.Items.Clear();
//DropDownList3.SelectedValue = null;
if (DDL_OutBreak_Monday.SelectedValue == "----")
{
DDL_OutBreak_Monday.SelectedValue = DateTime.Parse("00:00:00").ToShortTimeString();
}
if (DDL_InBreak_Monday.SelectedValue == "----")
{
DDL_InBreak_Monday.SelectedValue = DateTime.Parse("00:00:00").ToShortTimeString();
}
DateTime MondayDDL4 = DateTime.Parse(DDL_Out_Monday.SelectedValue);
DateTime MondayDDL3 = DateTime.Parse(DDL_InBreak_Monday.SelectedValue);
DateTime MondayDDL2 = DateTime.Parse(DDL_OutBreak_Monday.SelectedValue);
DateTime MondayDDL1 = DateTime.Parse(DDL_In_Monday.SelectedValue);
//DDL1 = DateTime.Parse(DDL_In_Tuesday.SelectedValue);// END POINT---------------------------END POINT
String BreakStart = DDL_OutBreak_Monday.SelectedValue;
String BreakEnd = DDL_InBreak_Monday.SelectedValue;
DateTime BreakStartDT = DateTime.Parse(BreakStart);
DateTime BreakEndDT = DateTime.Parse(BreakEnd);
DateTime FromCompHours = DateTime.Parse("6:30:00");
DateTime ToCompHours = DateTime.Parse("16:30:00");
Label1.Text = "";
Label2.Text = "";
Label3.Text = "";
LabelMondayREG.Text = "";
LabelMondayCALL.Text = "";
//int result = DateTime.Compare(DDL1, DDL2);
if ((MondayDDL1 <= FromCompHours) & (MondayDDL4 >= ToCompHours))//Comp time at both ends
{
Label2.Text = FromCompHours.Subtract(MondayDDL1).ToString(); //finds comp hours before 6:30 WORKS
Label3.Text = MondayDDL4.Subtract(ToCompHours).ToString(); //finds comp hours after 16:30 WORKS
LabelMondayREG.Text = ("10:00:00");
//LabelHolder.Text = (DateTime.Parse(Label2.Text)) + (DateTime.Parse(Label3.Text)).ToString(); //adds the two comp hours together
//TimeSpan SubtractReg = DDL2.Subtract(DDL1); //finds the difference of from minus to
DateTime To = DateTime.Parse(Label2.Text);//convert text to datetime of earlier time
DateTime From = DateTime.Parse(Label3.Text);//convert text to datetime of later time
LabelMondayCALL.Text = (To.TimeOfDay + From.TimeOfDay).ToString();
//LabelMondayCALL.Text = "10:00:00";
if ((BreakStartDT != DateTime.Parse("00:00:00")) & (BreakEndDT != DateTime.Parse("00:00:00")))
{
//DateTime MondayBreak = MondayDDL3.Subtract(MondayDDL2);
if ((MondayDDL2 <= FromCompHours) & (MondayDDL3 <= FromCompHours)) //Start before 6:30 end after 16:30 w/ break before 6:30
{
LabelMondayCALL.Text = TimeSpan.Parse(LabelMondayCALL.Text).Subtract(MondayDDL3.Subtract(MondayDDL2)).ToString();
//LabelMondayCALL.Text = "error1"; //(DateTime.Parse(LabelMondayCALL.Text)).ToString();
}
if ((ToCompHours >= MondayDDL2) & (MondayDDL2 >= FromCompHours) & (ToCompHours >= MondayDDL3) & (MondayDDL3 >= FromCompHours)) //Start before 6:30 end after 16:30 /w break between 6:30 and 16:30
{
LabelMondayREG.Text = TimeSpan.Parse(LabelMondayREG.Text).Subtract(MondayDDL3.Subtract(MondayDDL2)).ToString();
}
if ((MondayDDL2 >= ToCompHours) & (MondayDDL3 >= ToCompHours)) //Start before 6:30 end after 16:30 /w break after 16:30
{
LabelMondayCALL.Text = TimeSpan.Parse(LabelMondayCALL.Text).Subtract(MondayDDL3.Subtract(MondayDDL2)).ToString();
}
if ((MondayDDL2 <= FromCompHours) & (MondayDDL3 >= FromCompHours) & (MondayDDL3 <= ToCompHours))
{
LabelMondayCALL.Text = TimeSpan.Parse(LabelMondayCALL.Text).Subtract(FromCompHours.Subtract(MondayDDL2)).ToString();
LabelMondayREG.Text = TimeSpan.Parse(LabelMondayREG.Text).Subtract(MondayDDL3.Subtract(FromCompHours)).ToString();
}
if ((MondayDDL2 <= ToCompHours) & (MondayDDL2 >= FromCompHours) & (MondayDDL3 >= ToCompHours))
{
LabelMondayCALL.Text = TimeSpan.Parse(LabelMondayCALL.Text).Subtract(ToCompHours.Subtract(MondayDDL2)).ToString();
LabelMondayREG.Text = TimeSpan.Parse(LabelMondayREG.Text).Subtract(MondayDDL3.Subtract(ToCompHours)).ToString();
}
}

How to get 14 days prior to the given date avoiding holidays

In my system ,the due date of the bill must be 14 days after the issued date.
I have due date and I want to know issued date .
I have to calculate :
issued date = 14 days prior to the due date
but 14 days must be business days ,not holidays.
Holidays is stored in a table 'tblHolidayMaster' like this,
Date Description
2012/05/13 Mother's
Day2012/06/02 Saturnday2012/12/25 Christmas
How can I calculate the issued date avoiding holidays?
Thank you for all of your interests and replies.
I would calculate the Date using a function like the one below (which i use)
public static DateTime AddBusinessDays(DateTime date, int days)
{
if (days == 0) return date;
if (date.DayOfWeek == DayOfWeek.Saturday)
{
date = date.AddDays(2);
days -= 1;
}
else if (date.DayOfWeek == DayOfWeek.Sunday)
{
date = date.AddDays(1);
days -= 1;
}
date = date.AddDays(days / 5 * 7);
int extraDays = days % 5;
if ((int)date.DayOfWeek + extraDays > 5)
{
extraDays += 2;
}
int extraDaysForHolidays =-1;
//Load holidays from DB into list
List<DateTime> dates = GetHolidays();
while(extraDaysForHolidays !=0)
{
var days = dates.Where(x => x >= date && x <= date.AddDays(extraDays)).Count;
extraDaysForHolidays =days;
extraDays+=days;
}
return date.AddDays(extraDays);
}
Haven't tested the ast section that does the holidays
I went with the straight forward looping solution, so it will be slow for long intervals. But for short intervals like 14 days, it should be quite fast.
You need to pass in the holidays in the constructor. An instance of BusinessDays is immutable and can be reused. In practice you probably will use an IoC singleton or a similar construct to get it.
AddBusinessDays throws an ArgumentException if the start date is a non business day, since you didn't specify how to treat that case. In particular AddBusinessDays(0) on a non business day would have strange properties otherwise. It'd either break time reversal symmetry, or return a non business day.
public class BusinessDays
{
private HashSet<DateTime> holidaySet;
public ReadOnlyCollection<DayOfWeek> WeekendDays{get; private set;}
public BusinessDays(IEnumerable<DateTime> holidays, IEnumerable<DayOfWeek> weekendDays)
{
WeekendDays = new ReadOnlyCollection<DayOfWeek>(weekendDays.Distinct().OrderBy(x=>x).ToArray());
if(holidays.Any(d => d != d.Date))
throw new ArgumentException("holidays", "A date must have time set to midnight");
holidaySet = new HashSet<DateTime>(holidays);
}
public BusinessDays(IEnumerable<DateTime> holidays)
:this(holidays, new[]{DayOfWeek.Saturday, DayOfWeek.Sunday})
{
}
public bool IsWeekend(DayOfWeek dayOfWeek)
{
return WeekendDays.Contains(dayOfWeek);
}
public bool IsWeekend(DateTime date)
{
return IsWeekend(date.DayOfWeek);
}
public bool IsHoliday(DateTime date)
{
return holidaySet.Contains(date.Date);
}
public bool IsBusinessDay(DateTime date)
{
return !IsWeekend(date) && !IsHoliday(date);
}
public DateTime AddBusinessDays(DateTime date, int days)
{
if(!IsBusinessDay(date))
throw new ArgumentException("date", "date bust be a business day");
int sign = Math.Sign(days);
while(days != 0)
{
do
{
date.AddDays(sign);
} while(!IsBusinessDay(date));
days -= sign;
}
return date;
}
}
I think that is what you required. It is simple and I have tested it and it is working... And it is not a bad approach to write a function or SP in databases rather to write the complex code in C#... (change column name of date as in your db.)
Make it function or SP as what you want.
Note: Comment the check of 'Saturday' and 'Sunday'. If it is already added in your table reocrds.
declare #NextWorkingDate datetime
declare #CurrentDate datetime
set #CurrentDate = GETDATE()
set #NextWorkingDate = #CurrentDate
declare #i int = 0
While(#i < 14)
Begin
if(((select COUNT(*) from dbo.tblHolidayMaster where convert(varchar(10),[Date],101) like convert(varchar(10),#NextWorkingDate,101)) > 0) OR DATENAME(WEEKDAY,#NextWorkingDate) = 'Saturday' OR DATENAME(WEEKDAY,#NextWorkingDate) = 'Sunday')
Begin
print 'a '
print #NextWorkingDate
set #NextWorkingDate = #NextWorkingDate + 1
CONTINUE
End
else
Begin
print 'b '
print #NextWorkingDate
set #NextWorkingDate = #NextWorkingDate + 1
set #i = #i + 1
CONTINUE
End
End
print #NextWorkingDate
I calculate the issued date avoid your holiday from your table 'tblHolidayMaster' only.
int addDay = -14;
DateTime dtInputDay = System.DateTime.Now;//Your input day
DateTime dtResultDate = new DateTime();
dtResultDate = dtInputDay.AddDays(addDay);
bool result = false;
string strExpression;
DataView haveHoliday;
while (!result) {
strExpression = "Date >='" + Convert.ToDateTime(dtResultDate.ToString("yyyy/MM/dd")) + "' and Date <='" + Convert.ToDateTime(dtInputDay.ToString("yyyy/MM/dd")) + "'";
haveHoliday = new DataView(tblHolidayMaster);
haveHoliday.RowFilter = strExpression;
if (haveHoliday.Count == 0) {
result = true;
} else {
addDay = -(haveHoliday.Count);
dtInputDay = dtResultDate.AddDays(-1);
dtResultDate = dtResultDate.AddDays(addDay);
}
}
Your issued date is dtResultDate
Try the following link,
http://www.c-sharpcorner.com/uploadfile/tirthacs/difference-between-two-dates-excluding-weekends/

Count of days intersecting between two date ranges

Would anyone have any ideas of how to best calculate the amount of days that intersect between two date ranges?
Here's a little method I wrote to calculate this.
private static int inclusiveDays(DateTime s1, DateTime e1, DateTime s2, DateTime e2)
{
// If they don't intersect return 0.
if (!(s1 <= e2 && e1 >= s2))
{
return 0;
}
// Take the highest start date and the lowest end date.
DateTime start = s1 > s2 ? s1 : s2;
DateTime end = e1 > e2 ? e2 : e1;
// Add one to the time range since its inclusive.
return (int)(end - start).TotalDays + 1;
}
Obtain a new range, defined by the later of the beginnings and the earlier of the ends, and determine the number of days since the beginning of the epoch for each day in that new range.
The difference is the number of days in the intersection. Accept only positive values.
Edited to take into account ranges instead of individual dates.
Here is an example from R. That might clarify the answer.
c_st = as.POSIXct("1996-10-14")
c_ed = as.POSIXct("1996-10-19")
d_st = as.POSIXct("1996-10-17")
d_ed = as.POSIXct("1999-10-22")
max(range(c_st,c_ed ))-min(range(d_st,d_ed) ) >= 0 & min(range(c_st,c_ed )) < max(range(d_st,d_ed) )
True would indicate that they intersect, False otherwise.
[r]
If I understand your question, you're asking for the number of days that overlap two date ranges, such as:
Range 1 = 2010-1-1 to 2010-2-1
Range 2 = 2010-1-5 to 2010-2-5
in this example the number of intersecting days would be 28 days.
Here is a code sample for that example
DateTime rs1 = new DateTime(2010, 1, 1);
DateTime re1 = new DateTime(2010, 2, 1);
DateTime rs2 = new DateTime(2010, 1, 5);
DateTime re2 = new DateTime(2010, 2, 5);
TimeSpan d = new TimeSpan(Math.Max(Math.Min(re1.Ticks, re2.Ticks) - Math.Max(rs1.Ticks, rs2.Ticks) + TimeSpan.TicksPerDay, 0));
The question asks between two date Ranges not two Dates. (Edited in response to comments)
So if you have 2 Date Ranges (r1s,r1e), you need to determine which starts first, Is there overlap, and what is the overlap.
double overlap(DateTime r1s, DateTime r1e, DateTime r2s, DateTime r1e){
DateTime t1s,t1e,t2s,t2e;
if (rs1<rs2) //Determine which range starts first
{
t1s = r1s;
t1e = r1e;
t2s = r2s;
t2e = r2e;
}
else
}
t1s = r2s;
t1e = r2e;
t2s = r1s;
t2e = r1e;
}
if (t1e<t2s) //No Overlap
{
return -1;
}
if (t1e<t2e) //Partial Overlap
}
TimeSpan diff = new TimeSpan(t1e.Ticks - t2s.Ticks);
{
else //Range 2 totally withing Range 1
}
TimeSpan diff = new TimeSpan(t2e.Ticks - t2s.Ticks);
{
double daysDiff = diff.TotalDays;
return daysDiff;
}

Categories