VB.net Get total time between two time spans - vb.net

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)

EDIT:
Sorry, I misunderstood your question. I think this is what you are looking for.
Here is your DateRange class:
Public Class DateRange
Public Property StartTime As DateTime
Public Property EndTime As DateTime
Public ReadOnly Property NumberOfHours As Decimal
Get
Dim result As Double
result += (EndTime - StartTime).Hours
result += (EndTime - StartTime).Minutes / 60
result += (EndTime - StartTime).Seconds / 3600
Return result
End Get
End Property
End Class
This would be the C# function from the link, rewritten in VB:
Private Function GetIntersectionRange(range1 As DateRange, range2 As DateRange) As DateRange
Dim iRange As New DateRange()
iRange.StartTime = If(range1.StartTime < range2.StartTime, range2.StartTime, range1.StartTime)
iRange.EndTime = If(range1.EndTime < range2.EndTime, range1.EndTime, range2.EndTime)
If iRange.StartTime > iRange.EndTime Then iRange = Nothing
Return iRange
End Function
Here is a little snippet of code to do the calculation you asked and write the answer to the console:
Dim firstDate As New DateRange With {.StartTime = New DateTime(2013, 1, 1, 8, 30, 0), .EndTime = New DateTime(2013, 1, 1, 23, 30, 0)}
Dim secondDate As New DateRange With {.StartTime = New DateTime(2013, 1, 1, 22, 0, 0), .EndTime = New DateTime(2013, 1, 2, 6, 0, 0)}
Dim result As DateRange = GetIntersectionRange(firstDate, secondDate)
Console.WriteLine(result.NumberOfHours)

Like this?
Dim d1 As DateTime = "1/22/2018 8:30:00 AM"
Dim d2 As DateTime = "1/29/2018 5:30:00 PM"
Dim ts As TimeSpan = d2.Subtract(d1)
MessageBox.Show("Total Hours are " & Convert.ToDouble(Math.Round(ts.TotalHours, 2)))
Just play around with it

Related

How to change date in IF statement

I wish to change startDate depending on the day of the week. Here is what I've tried, the error I get is BC30311: Value of type 'Integer' cannot be converted to 'Date'.
Dim curr As Date = Date.Now
Dim day As String = Date.Today.DayOfWeek.ToString()
Dim startTime As New Date
If day="saturday" Then
startTime=(curr.Year, curr.Month, curr.Day, 17, 0, 0)
Else
startTime=(curr.Year, curr.Month, curr.Day, 13, 0, 0)
End If
Dim endTime As New Date(curr.Year, curr.Month, curr.Day, 21, 59, 0)
If (curr >= startTime) And (curr <= endTime) Then
'''Some Code
I simply need to change startDate to 13:00 hours for Saturdays. Any help appreciated
This is a better way to write code to do what you appear to want to do:
Dim currentDay = Date.Today
Dim startTime = currentDay.AddHours(If(currentDay.DayOfWeek = DayOfWeek.Saturday, 17, 13))
Dim endTime = currentDay.AddHours(21).AddMinutes(59)
Dim currentTime = Date.Now
If currentTime >= startTime AndAlso currentTime <= endTime Then

How do I get the start date and end date of the current week?

I have a function that returns the current week of the year where we are now, thanks to one of the answers in this forum. Now I need to get the initial date of that week and the final date of that week.
How can I accomplish this?
Protected Friend Function obtenerNumeroSemanas(ByVal dt As DateTime)
Dim cal As Calendar = CultureInfo.InvariantCulture.Calendar
Dim d As DayOfWeek = cal.GetDayOfWeek(dt)
If (d >= DayOfWeek.Monday) AndAlso (d <= DayOfWeek.Wednesday) Then
dt = dt.AddDays(3)
End If
Return cal.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)
End Function
Dim dayOfWeek = Cint(DateTime.Today.DayOfWeek)
Dim startOfWeek = DateTime.Today.AddDays(-1 * dayOfWeek)
Dim endOfWeek = DateTime.Today.AddDays(7 - dayOfWeek).AddSeconds(-1)
Console.WriteLine(startOfWeek)
Console.WriteLine(endOfWeek)
Using today's date (2016-06-19) results in
2016-06-19 12:00:00 AM
2016-06-25 11:59:59 PM
Dim dayOfWeek = CInt(DateTime.Today.DayOfWeek)
Dim startOfWeek = DateTime.Today.AddDays(+1 * dayOfWeek).ToShortDateString
Dim endOfWeek = DateTime.Today.AddDays(4 + dayOfWeek).AddSeconds(+1).ToShortDateString
MessageBox.Show(startOfWeek)
MessageBox.Show(endOfWeek)
that to get the next monday date and the next friday
Dim result$ = DateTime.Today.AddMonths(-1).ToString("dd-MMM-yyyy")

How to count someday to someday without holiday and Saturday , Sunday (VB) by use Date time picker

enter image description hereHow to count someday to someday without holiday and Saturday , Sunday (VB) by use Date time picker
for leave people system
help me please!
from the picture
left is date start and right is end date
then if I select date both. then count day on the textbox... without Sunday Saturday and Holiday that on Access database...
Count days from start to finish that are not Saturday or Sunday:
Dim startDate As Date = New DateTime(2016, 1, 1)
Dim endDate As Date = DateTime.Now
Dim currentDate = startDate
Dim daysWithoutSatOrSun As Integer = 0
Do
If currentDate.DayOfWeek <> DayOfWeek.Saturday AndAlso currentDate.DayOfWeek <> DayOfWeek.Sunday Then
daysWithoutSatOrSun += 1
End If
currentDate = currentDate.AddDays(1)
Loop Until currentDate > endDate
MessageBox.Show("Days " & daysWithoutSatOrSun)
One readable option is to use LINQ:
Dim days As Int32 = (d2 - d1).Days
Dim weekend = {DayOfWeek.Saturday, DayOfWeek.Sunday }
Dim nonWeekendDays = From d in Enumerable.Range(0, days + 1)
Select day = d1.Date.AddDays(d)
Where Not weekend.Contains(day.DayOfWeek)
Dim countOfDays As Int32 = nonWeekendDays.Count()
If you have List(Of Date) which contains the holidays you can add:
Where Not weekend.Contains(day.DayOfWeek) AndAlso Not holidays.Contains(day)

Fun Logic to minus date with date and get the diffdate vb.net

Ok I cannot think of a algorithm to do this using vb.net.
so here is the 3 variable
Dim DateFrom as date = '01/09/2015'
Dim DateNow as date = Date.Now
Dim Holiday() as date '' <-- List of holiday dates
So what I want to do is I want to get the "Day" diffdate From DateFrom and DateNow and excluding the minus the date in the Holiday() array and also saturday Sunday.
so let say my DateFrom is '01/09/2015' which is Tuesday and my
DateNow is '09/09/2015' which is also tuesday and inside the Holiday() array there's '4/09/2015' Friday. the output of diffdate is suppose to be 5 Day since since (DateNow ---Difference Day minus Holiday()array and also minus saturday and sunday -- DateFrom)
I scratches my head about 152.5 times and still cannot find the way to do this.
I think you can solve this problem using something like this:
Dim intTotalDays As Integer = 0
Dim dtStartDate As New DateTime(2015, 10, 1)
Dim dtEndDate As New DateTime(2015, 10, 31)
Dim Holidays As DateTime() = {
New DateTime(2015, 10, 15),
New DateTime(2015, 10, 17)
}
For i As Integer = 0 To DateDiff(DateInterval.Day, dtStartDate, dtEndDate)
Dim dtDay As DateTime = DateAdd(DateInterval.Day, i, dtStartDate)
If Not dtDay.DayOfWeek = DayOfWeek.Saturday And Not dtDay.DayOfWeek = DayOfWeek.Sunday And Not Holidays.Contains(dtDay) Then
intTotalDays += 1
End If
Next i
MsgBox(intTotalDays)
So you want to determine the number of working-days between two dates?
You can use following LINQ query:
Dim DateFrom As Date = #9/1/2015#
Dim Holiday() As Date = {#9/4/2015#}
Dim Weekend() As DayOfWeek = {DayOfWeek.Saturday, DayOfWeek.Sunday}
Dim days As Int32 = (Date.Today - DateFrom).Days + 1 '+ 1 to include end day '
Dim workingDaysBetween =
From d In Enumerable.Range(0, days)
Let day = DateFrom.AddDays(d)
Where Not Weekend.Contains(day.DayOfWeek) AndAlso Not Holiday.Contains(day)
Dim countDays As Int32 = workingDaysBetween.Count()

How to compare just the date part and not the time of two Dates?

I want to compare just the date part (and Not the time) of two VB.NET Date objects.
Is there a way to do that?
Just take the date part of each via the Date property and compare the two:
date1.Date.CompareTo(date2.Date)
Or:
If date1.Date < date2.Date Then
You could also use TimeSpan
Dim ts As TimeSpan
ts = dt1 - dt2
ts.Days will now have the difference of the two dates as whole days.
Compare the DateTime.Date properties.
Change the txt1 date to format dd/mm/yyyy using myDateTime.ToShortDateString() so that both the dates will be in same format.
then :
if (DateTime.Compare(date1, date2) > 0)
// which means ("date1 > date2")
if (DateTime.Compare(date1, date2) == 0)
//which means ("date1 == date2");
if (DateTime.Compare(date1, date2) < 0)
//which means ("date1 < date2");
Dim backDateCount As Integer = DateDiff(DateInterval.Day, CDate(dtpCheckIn.SelectedDate.Value).Date, Date.Now.Date)
Date.Now.Date: #12/4/2018 12:00:00 AM#
Date.Now: #12/4/2018 03:23:34 PM#
Dim date1, date2 As Date
date1 = Date.Parse(dtpStart.Text)
date2 = Date.Parse(dtpEnd.Text)
If (DateTime.Compare(date1, date2) > 0) Then ' which means ("date1 > date2")
MessageBox.Show("يجب تحديد الفترة للتاريخ بشكل صحيح ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.RtlReading)
Exit Sub
End If