I was wondering if there is a function with VB.NET that can tell me the total time that two different time spans have in common.
for example, I have these two different time spans:
1st Date : (2013-01-01 8:30 AM) - (2013-01-01 11:30PM)
2nd Date : (2013-01-01 10:00 PM) - (2013-01-02 6:00 AM)
Can VB.NET tell me that the answer is 1 hour and 30 mins? (perhaps in decimal) It is 1 hour and 30 minutes because up to 10:00PM in the evening and 11:30 in the evening falls in with the other time span.
Summary:
I just need a function that will tell me how many hours in a certain timespan is a part of the night shift. (that's 10:00 PM to 6:00 AM).
This functionality is available to all .Net languages via the TimeSpan class:
eg.:
result = (dt2 - dt1).TotalHours
When you subtract two dates you get a TimeSpan. The TotalHours property of the TimeSpan gives you the number of hours, or part thereof.
Check out the docs: http://msdn.microsoft.com/en-us/library/269ew577(v=vs.110).aspx
Date1 and Date2 represents the first time span and Date2 and Date3 represent the second time span. If the order of the dates are changed you will have to define an analogous else to the first if.
Dim date1 As Date = #1/1/2013 8:30:00 AM#
Dim date2 As Date = #1/1/2013 11:30:00 PM#
Dim date3 As Date = #1/1/2013 10:00:00 PM#
Dim date4 As Date = #1/2/2013 6:00:00 AM#
Dim timePeriod As TimeSpan
If date3.Date >= date1.Date And date3.Date <= date2.Date Then
If date4.Date <= date2.Date Then
timePeriod = date4.TimeOfDay - date3.TimeOfDay
Else
timePeriod = date2.TimeOfDay - date3.TimeOfDay
End If
End If
Msgbox(timePeriod.ToString)
EDIt: Just timePeriod = date4- date3 will convert the difference into timespan
EDIT 2:The code above would have returned date2-date3 even if there there was no common time span. The code below would return 0 in such a case. Also when comparing two Date variables in an If statement, the TimeOfDay part is neglected.
Dim date1 As Date = #1/1/2013 8:30:00 AM#
Dim date2 As Date = #1/1/2013 11:30:00 PM#
Dim date3 As Date = #1/1/2013 10:00:00 PM#
Dim date4 As Date = #1/2/2013 6:00:00 AM#
Dim timePeriod As TimeSpan
If date3 >= date1 And date3 <= date2 Then
If date4 <= date2 Then
timePeriod = date4 - date3
ElseIf date3 < date2 Then
timePeriod = date2 - date3
ElseIf date3.Date = date2.Date Then
If date3.TimeOfDay < date2.TimeOfDay Then
timePeriod = date2 - date3
Else
timePeriod = TimeSpan.FromDays(0)
End If
Else
timePeriod = TimeSpan.FromDays(0)
End If
End If
MsgBox(timePeriod.ToString)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With