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)
Related
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
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
I am looking for a way to store the last workday of each month between two "Input dates", and I need to store them as Strings in an array. I have tried to use the Worksheet function "Workday", but my input dates are of the format dd-mm-yyy, and I coundn't get it to work..
Any help is appreciated, Thanks.
Too bad, i've assumed that your VB.NET tag was the correct one, now it's removed. However, if someone needs something similar in .NET this might be helpful:
Dim fromDate = DateTime.Today.AddYears(-1) ' sample days
Dim toDate = DateTime.Today
Dim startDay = New Date(fromDate.Year, fromDate.Month, 1).AddMonths(1)
Dim endDay = New Date(toDate.Year, toDate.Month, 1).AddMonths(1)
Dim monthsBetween As Int32 = GetMonthsBetween(startDay, endDay)
Dim nonWorkingDays = {DayOfWeek.Saturday, DayOfWeek.Sunday}
Dim workingDatesBetween As New List(Of String)
For month As Int32 = 0 To monthsBetween
Dim d As DateTime = startDay.AddMonths(month)
' look into last months last days, shorter way
Dim lastWorkingDay As Date = Date.MinValue
While lastWorkingDay = Date.MinValue
d = d.AddDays(-1) ' look backwards into the last month to find the last working-day
If Not nonWorkingDays.Contains(d.DayOfWeek) Then
lastWorkingDay = d
workingDatesBetween.Add(lastWorkingDay.ToString("dd-MM-yyy", CultureInfo.InvariantCulture))
End If
End While
Next
Dim result = workingDatesBetween.ToArray()
This method was used to determine the number of months between two dates:
Public Shared Function GetMonthsBetween(date1 As DateTime, date2 As DateTime) As Int32
Dim months = Math.Abs(((date1.Year - date2.Year) * 12) + date1.Month - date2.Month)
Return months
End Function
or as reusable method (although i doubt that someone needs this method often):
Public Shared Function GetLastWorkingDatesInMonthBetween(fromDate As Date, toDate As Date) As Date()
Dim startDay = New Date(fromDate.Year, fromDate.Month, 1).AddMonths(1)
Dim endDay = New Date(toDate.Year, toDate.Month, 1).AddMonths(1)
Dim monthsBetween As Int32 = GetMonthsBetween(startDay, endDay)
Dim nonWorkingDays = {DayOfWeek.Saturday, DayOfWeek.Sunday}
Dim workingDatesBetween As New List(Of Date)
For month As Int32 = 0 To monthsBetween
Dim d As DateTime = startDay.AddMonths(month)
' look into last months last days, shorter way
Dim lastWorkingDay As Date = Date.MinValue
While lastWorkingDay = Date.MinValue
d = d.AddDays(-1) ' look backwards into the last month to find the last working-day
If Not nonWorkingDays.Contains(d.DayOfWeek) Then
lastWorkingDay = d
workingDatesBetween.Add(d)
End If
End While
Next
Return workingDatesBetween.ToArray()
End Function
Now you get the String() from the Date() via Array.ConvertAll:
Dim allNonWorkingDates = GetLastWorkingDatesInMonthBetween(DateTime.Today.AddYears(-1), DateTime.Today)
Dim result As String() = Array.ConvertAll(allNonWorkingDates, Function(d) d.ToString("dd-MM-yyy", CultureInfo.InvariantCulture))
Result with the sample year above:
30-09-2013
31-10-2013
29-11-2013
31-12-2013
31-01-2014
28-02-2014
31-03-2014
30-04-2014
30-05-2014
30-06-2014
31-07-2014
29-08-2014
30-09-2014
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.
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.