Create time duration from date time picker - vb.net

I am creating a VB Class - Employees work time for a single shift which occurs during one working day. does not cross midnight, with breaks of total duration but no specified time . It has 3 date/time pickers Start Time, Finish Time, Break duration time. I want to deduct start time from finish time and deduct break duration to give total time worked. Formatted HH:MM I am going wrong somewhere but cannot put my finger on it, could you please help.
Dim TimeIn As Date = StartTime.Value
Dim TimeOut As Date = FinishTime.Value
Dim Break As Date = BreakPicker.Value
Dim TimeNow As Date = DateTime.Now
Dim TempTime As Date = TimeNow + Break
Dim BreakDuration As System.TimeSpan = TempTime - TimeNow
Dim diff As System.TimeSpan = TimeOut.Subtract(TimeIn)
Dim diff1 As System.TimeSpan = TimeOut - TimeIn
Dim diff2 As Integer = ((TimeOut - BreakDuration) - TimeIn).TotalMinutes
Dim diff3 As System.TimeSpan = TimeNow.Subtract(TimeOut)
If TimeOut <= TimeIn Then
MsgBox("Invalid time")
Exit Sub
End If
Dim TotMins As Integer = diff2
Dim Hours As Integer = Math.Floor(TotMins / 60)
Dim Minutes As Integer = TotMins Mod 60
HoursRequiredBox.Text = (Hours & "h : " & Minutes & "m".ToString())

I would do it by accessing the properties of the datepicker.
So for hours, you can use:
Dim hour1 As Integer = 0
Dim hour2 As Integer = 0
Dim hourTotal As Integer = 0
hour1 = datepicker1.value.hour
hour2 = datepicker2.value.hour
hourTotal = hour2 - hour1
Same goes for the minute. Just replace .hour to .minute

Related

vb.net timeserial only (hour, minute)

How get format time only hour and minute.
Dim xDateTime As Date
xDateTime = Now
Dim ret As String = TimeSerial(xDateTime.Hour, xDateTime.Minute, xDateTime.Minute).ToString
ret = ret.Remove(xDateTime.Minute)
MsgBox(ret)

VB.NET How to get total hours and minutes in Listbox

Please help! I need to get the total hours and minutes which format is "HH:mm" from ListBox, for example:
11:20
22:40
34:00
Total: 68:00
I tried to use Datetime and TimeSpan, but it has error :
"The DateTime represented by the string is not supported in calendar
System.Globalization.GregorianCalendar."
Here is my code:
ListBox_monthtime.Items.Add("11:20")
ListBox_monthtime.Items.Add("22:40")
ListBox_monthtime.Items.Add("34:00")
'SUM TIMES IN LISTBOX
Dim MyDateTimeMonthly As DateTime
Dim MyTimeSpanMonthly As New TimeSpan
For Each S As String In ListBox_monthtime.Items
MyDateTimeMonthly = DateTime.ParseExact(S, "HH:mm", System.Globalization.CultureInfo.InvariantCulture)
MyTimeSpanMonthly = MyTimeSpanMonthly.Add(New TimeSpan(MyDateTimeMonthly.Day, MyDateTimeMonthly.Hour, MyDateTimeMonthly.Minute, 0))
Next
monthtime_txt.Text = (MyTimeSpanMonthly.Days * 24 + MyTimeSpanMonthly.Hours) & ":" & MyTimeSpanMonthly.Minutes
Maybe this can help instead:
ListBox_monthtime.Items.Add("11:43")
ListBox_monthtime.Items.Add("22:56")
ListBox_monthtime.Items.Add("34:21")
Dim totalHours As Integer
Dim totalMinutes As Integer
For Each S As String In ListBox_monthtime.Items
totalHours += S.Split(":")(0)
totalMinutes += S.Split(":")(1)
Next
Dim remainder = totalMinutes Mod 60
totalHours += totalMinutes / 60
Dim totalTime = totalHours & ":" & remainder.ToString("D2")
monthtime_txt.Text = totalTime
You would still be casting Strings-Integers though, so I would put that inside a Try/Catch
You cannot create a DateTime or a Timespan from a string using an hour value that is greater than 24. You will need to parse the input yourself and convert it to a valid string to be used by TimeSpan.parse().
Dim TotalTime As TimeSpan = TimeSpan.Zero
For Each item As String In ListBox_monthtime.Items
TotalTime = TotalTime.Add(TimeSpan.Parse(FormatTimeString(item)))
Next
Me.monthtime_txt.Text = $"{CInt(TotalTime.TotalHours).ToString}:{TotalTime.Minutes}"
Private Function FormatTimeString(TimeString As String) As String
Dim timeArr() As String = TimeString.Split(":")
If CInt(timeArr(0)) > 24I Then
Dim d As Int32 = CInt(timeArr(0)) \ 24I
FormatTimeString = $"{d}:{(CInt(timeArr(0)) - (24I * d)).ToString}:{timeArr(1)}:00"
Else
FormatTimeString = TimeString
End If
End Function

How to compare two time in vb.net

I have 1 String in VB.net
Dim str As String = "2014/08/15 19:45"
I have 2 time
Dim startDate As String = "6:30"
Dim endDate As String = "22:00"
How to compare "str" with "startDate" & "endDate" ?
First, you have strings not DateTimes or TimeSpan. But you need both if you want to compare them. So use Date.Parse, Date.ParseExact (or the ...TryParse versions to check invalid data):
Dim str As String = "2014/08/15 19:45"
Dim dt1 = Date.ParseExact(str, "yyyy/MM/dd HH:mm", CultureInfo.InvariantCulture)
Dim startDate As String = "6:30"
Dim tsStart = TimeSpan.Parse(startDate)
Dim endDate As String = "22:00"
Dim tsEnd = TimeSpan.Parse(endDate)
Now you can compare them:
If dt1.TimeOfDay >= tsStart AndAlso dt1.TimeOfDay <= tsEnd Then
' Yes, 19:45 is between 6:30 and 22:00 '
End If
First, you should be using dates to store the values. Then it's a simple matter of checking the time components. Note that the implementation below is inclusive (i.e. if the time is exactly the start or end time, it will print the message.
Dim dateToCheck As Date = Date.Parse("2014/08/15 19:45")
' The date portion doesn't matter, so I'm just using 1/1/1970.
Dim startTimeDate As Date = New Date(1970, 1, 1, 6, 30, 0)
Dim endTimeDate As Date = New Date(1970, 1, 1, 22, 0, 0)
Dim afterOrEqualToStartTime As Boolean = (dateToCheck.Hour >= startTimeDate.Hour) And (dateToCheck.Minute >= startTimeDate.Minute) And (dateToCheck.Second >= startTimeDate.Second)
Dim beforeOrEqualToEndTime As Boolean = (dateToCheck.Hour <= endTimeDate.Hour) And (dateToCheck.Minute <= endTimeDate.Minute) And (dateToCheck.Second <= endTimeDate.Second)
If (afterOrEqualToStartTime And beforeOrEqualToEndTime) Then
MsgBox("Date is between the start and end times")
End If
Dim str As String = "2014/08/15 19:45"
Dim time As DateTime = DateTime.Parse(str)
'here get the hour and minutes, and now you can compare with the others
Dim tmpTime As DateTime = time.ToString("t")
Comparing time is difficult using Date variables.
Using a data difference, with a tolerance, is one way to deal with binary time.
I use strings:
Dim dt As Date = "2014/08/15 22:45"
Dim s As String = dt.ToString("H:MM")
If s > "06:30" And s <= "22:00" Then
MsgBox("yes")
Else
MsgBox("no")
End If
note the leading 0 in 06:30 in the sample.

Subtract time in VB.net

I am trying to subtract two times.
Sub notifier(checkouttime As Label)
Dim checktime As New DateTime(checkouttime.Tag)
Dim currenttime As New DateTime(DateAndTime.TimeOfDay.ToString("hh:mm:ss"))
Dim balance As TimeSpan = checktime - currenttime
End Sub
on my checkouttime.tag has a time value of under this format "hh:mm:ss"
and I have to get the current time for today with the same format and I achieve it but when I need to subtract them I am getting an error.
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "08:00:58" to type 'Long' is not valid.
Thanks in advance
This will try to parse your DateTime string. You may need to save a date with time that you save to your Tag property.
Private Function Notifier(checkouttime As Label) As String
Dim checktime As DateTime
If DateTime.TryParse(checkouttime.Tag.ToString, checktime) Then
Dim currenttime As Date = Date.Now
Return (currenttime - checktime).ToString()
End If
Return "Bad Time String"
End Sub
Try this kind of format...
Dim date1 As Date = #2/14/2014 9:35:04 AM#
Dim date2 As Date = #2/28/2014 12:30:54 PM#
Dim duration As TimeSpan = date1 - date2
MsgBox(duration.ToString)
Nevermind, I have found another similar solution for my problem and here is how I solve it.
Sub notifier(checkouttime As Label)
Dim checktime As String = checkouttime.Tag
Dim splitcheck = Split(checktime, ":")
Dim currenttime As String = CStr(DateAndTime.TimeOfDay.ToString("hh:mm:ss"))
Dim splitcurrent = Split(currenttime, ":")
Dim checkMinutes, currentMinutes As Integer
checkMinutes = CDbl(splitcheck(0)) * 60 + CDbl(splitcheck(1)) + CDbl(splitcheck(2)) / 60
currentMinutes = CDbl(splitcurrent(0)) * 60 + CDbl(splitcurrent(1)) + CDbl(splitcurrent(2)) / 60
'Dim balance As String = checkkresult - currentresult
MsgBox(checkMinutes & " " & currentMinutes & ". While current time is: " & currenttime)
End Sub
I converted the time to minutes to achieve my goals.
Thanks for your answer guys.

Create HTML on Specific Time

If have the following Code:
Public Shared Function GetNextWeekDay() As Date
Dim value As Date = Date.Now
Do
value = value.AddDays(1)
Loop While (value.DayOfWeek = DayOfWeek.Saturday) Or (value.DayOfWeek = DayOfWeek.Sunday)
Return value
End Function
Public Shared Function DPLoadData() As String
Dim s As StringBuilder = New StringBuilder("<head><meta http-equiv=""content-type"" content=""text/html;charset=utf-8"" /><META HTTP-EQUIV=""REFRESH"" CONTENT=""900"">")
s.Append("<style type=""text/css"" media=""all""> body{font-family: Arial;}h4{font-size: 10pt;font-weight: bold;white-space: nowrap;margin-top: 0; margin-bottom: 10px;}")
s.Append("th{font-size: 9pt;font-weight: normal;text-align: center;white-space: nowrap;}td{font-size: 9pt;}.content td{border: solid 1px #dadada;}")
s.Append(".content th {border: solid 1px #dadada;background-image: url(""tbl_header_row_bg.gif""); background-repeat: repeat-x; white-space: nowrap;}</style></head>")
s.Append("<h3>" & "Daily Plan" & "</h3>")
Dim strCurrDay As String = ""
s.Append("<h5>" & strCurrDay & "</h5>")
Dim CurrDateFirstDay As Date = GetNextWeekDay()
strCurrDay = FormatDateTime(CurrDateFirstDay, DateFormat.LongDate)
s.Append("<h5>" & strCurrDay & "</h5>")
s.Append(LoadDataGroupByDate(CurrDateFirstDay))
Return s.ToString()
End Function
The function DPLoadData generates an HTML file with a table and fills it with bookings. Currently, the HTML file displays the bookings of tomorrow (e.g. if today is Monday, it displays the bookings for Tuesday and if today is Friday, it displays the bookings for Monday).
What i need is that the HMTL file gets generated at 5 p.m. For Example: If today is Monday, then the HTML file should be generated Monday at 5 p.m and should display the bookings for Tuesday until Tuesday 5 p.m and Tuesday at 5 p.m the file should be generated for wednesday and should display the bookings for wednesday until wednesday 5 p.m, and so on.
How can i do that? Please help.
My Solution:
Public Shared Function GetNextWeekDay() As Date
Dim value As Date = Date.Now
Dim intHour As Integer
Dim intMinute As Integer
Dim intSecond As Integer
intHour = 17
intMinute = 0
intSecond = 0
Dim newdatetime As DateTime = New Date(value.Year, value.Month, value.Day, intHour, intMinute, intSecond)
If DateTime.Now < newdatetime Then
If value.DayOfWeek = DayOfWeek.Saturday Then
value = value.AddDays(2)
Return value
End If
If value.DayOfWeek = DayOfWeek.Sunday Then
value = value.AddDays(1)
Return value
End If
Return value
ElseIf DateTime.Now > newdatetime Then
Do
value = value.AddDays(1)
Loop While (value.DayOfWeek = DayOfWeek.Saturday) Or (value.DayOfWeek = DayOfWeek.Sunday)
Return value
End If
End Function
As I understand your question, you are basically looking for a way to execute a program at a given time? If so, have a look at cron or the Windows scheduler, depending on the OS you are running this on.
Update: So basically you just need to compare the current time and check whether it is before 5pm. Then you should have a function which return the data from 5pm current day until 5pm tomorrow.
You might want to have a look at this VB tutorial for DateTime. Basically you need to compare the current time with a date time consisting of the current date at 5pm.
Update: Just extend your if condition to also check that today is not Saturday or Sunday. Here's a little code snippet I just whipped up. I am not really familiar with VB, so this might not be 100% correct, but I think you get the idea.
Public Function GetNextWeekDay() As Date
Dim value As Date = Date.Now
Dim intHour As Integer
Dim intMinute As Integer
Dim intSecond As Integer
intHour = 17
intMinute = 0
intSecond = 0
Dim newdatetime As DateTime = New Date(value.Year, value.Month, value.Day, intHour, intMinute, intSecond)
If value.DayOfWeek <> DayOfWeek.Saturday And value.DayOfWeek <> DayOfWeek.Sunday And DateTime.Now < newdatetime Then
Return value.Date
Else
Do
value = value.AddDays(1)
Loop While (value.DayOfWeek = DayOfWeek.Saturday) Or (value.DayOfWeek = DayOfWeek.Sunday)
Return value.Date
End If
End Function