vb.net timeadding from two textbox - vb.net

Please help me first before giving me a bad feedback.
I need to add two time from text box. But when I'm adding it only the minute was adding and not the hours.
Dim dt As DateTime = TxtDTEAP.Text
Dim wt As DateTime = TxtWTEAP.Text
Dim totalspan As New TimeSpan
Dim result As New DateTime
result = dt.AddMinutes(wt.Minute)
Me.TxtTRTEAP.Text = result
For example, the txtWTEAP.Text = 1:30 and txtDTEAP.Text = 2:50 the result should be 4:20 but the result showing on this code is 1:20 only.
Thank you so much!

Split the strings in the TextBoxes into an array. The first element will contain the hours and the second element will contain the minutes. The c following the split character tells the compiler this is a char not a string.
Use the constructor of the TimeSpan structure to create TimeSpans. The constructor takes 3 arguments, Hours as Integer, Minutes as Integer and Seconds as Integer.
Finally, we can do the addition.
Then display the result using .ToString with a format string. The \ is and escape character so it doesn't think the : is something else.
Private Sub GetTotalTime()
Dim parseTime1() As String = TxtDTEAP.Text.Split(":"c)
Dim parseTime2() As String = TxtWTEAP.Text.Split(":"c)
Dim dt As TimeSpan = New TimeSpan(CInt(parseTime1(0)), CInt(parseTime1(1)), 0)
Dim wt As TimeSpan = New TimeSpan(CInt(parseTime2(0)), CInt(parseTime2(1)), 0)
Dim result As TimeSpan = dt + wt
TxtTRTEAP.Text = result.ToString("h\:mm")
End Sub

Related

How to compare Time variables?

I have 3 variables of type DateTime or string type, in the form hh:mm:ss.
For example:
dT1="00:00:00"
dT2="20:59:59"
dT3="18:04:21"
How can I perform the following comparison?
dT1<= dT3 <= dT2 ??
Your example show String not DateTime. I put your strings in and array called TimeStrings. Then I created a List of TimeSpan. Looping through the strings I split each string on the colon, then created a new TimeSpan and added it to the list. I used the .Max method of the list to get the highest value in the list.
Private Sub OpCode()
'Constructor TimeSpan(Int32, Int32, Int32)
Dim dT1 = "00:00:00"
Dim dT2 = "20:59:59"
Dim dT3 = "18:04:21"
Dim TimeStrings = {dT1, dT2, dT3}
Dim Spans As New List(Of TimeSpan)
For Each s In TimeStrings
Dim Splits = s.Split(":"c)
Dim span As New TimeSpan(CInt(Splits(0)), CInt(Splits(1)), CInt(Splits(2)))
Spans.Add(span)
Next
Dim HighestValue = Spans.Max
MessageBox.Show(HighestValue.ToString)
End Sub
You can use the TimeSpan.Parse(), ParseExact(), TryParse() or TryParseExact() to convert the string to a TimeSpan value. The comparison is straightforward after that:
Add your string values to a collection (an Array or List of strings).
Dim dTs As String() = {"00:00:00", "23:59:59", "20:59:59", "23:10:21", "18:04:21"}
Dim max As TimeSpan = dTs.Select(
Function(s) TimeSpan.ParseExact(s, "hh\:mm\:ss", CultureInfo.InvariantCulture)).Max()
max will be 23:59:59
Of course you can order the TimeSpan value, in ascending order here:
Dim orderedTimeSpans =
dTs.Select(Function(s) TimeSpan.ParseExact(s, "hh\:mm\:ss", CultureInfo.InvariantCulture)).
OrderBy(Function(ts) ts).ToList()
orderedTimeSpans.ForEach(Sub(ts) Console.WriteLine(ts))
Which prints:
00:00:00
18:04:21
20:59:59
23:10:21
23:59:59
With TryParseExact(), if you're not sure whether the format is may not be correct (possibly, because the source of the values is not reliable - User input, for example):
Dim parsed As TimeSpan
Dim max As TimeSpan =
dTs.Select(Function(s) TimeSpan.TryParseExact(s, "hh\:mm\:ss",
CultureInfo.InvariantCulture, parsed)).Max(Function(t) parsed)
This also returns 23:59:59.
If one of the values cannot be parsed, it won't be evaluated by the Max() method.
E.g., if this is the input string "23.59:59", InvariantCulture and the format specified won't allow to return a valid TimeSpan, so the max value will be 23:10:21 instead.
The same, using TryParseExact(), but in extended form (using a loop):
Dim maxValue As TimeSpan = New TimeSpan()
Dim parsed As TimeSpan = New TimeSpan()
For Each value As String In dTs
If TimeSpan.TryParseExact(value, "hh\:mm\:ss", CultureInfo.InvariantCulture, parsed) Then
maxValue = If(TimeSpan.Compare(maxValue, parsed) > 0, maxValue, parsed)
End If
Next
You can try something like this:
Dim dT1 As DateTime = New DateTime(2020, 1, 1, 0, 0, 0) ' 00:00:00
Dim dT2 As DateTime = New DateTime(2020, 1, 1, 20, 59, 59) ' 20:59:59
Dim dT3 As DateTime = New DateTime(2020, 1, 1, 18, 04, 21) ' 18:04:21
If dT1 <= dT3 <= dT2 Then
'your code
End If
Hope, it helps :)

How to sum up all the datetime/time in a datagridview vb.net

I've been wondering how can I convert this line of code which compute the sum of an integer.
I need to sum up all my column data from the datagridview which is in a timespan format(0,0,0)
I'm getting an error
System.FormatException: 'Input string was not in a correct format.'
any help?
txtTotalTime.Text =
( From row As DataGridViewRow In DataGridView3.Rows
Where row.Cells(2).FormattedValue.ToString() <> String.Empty
Select Convert.ToInt32(row.Cells(2).FormattedValue)
).Sum().ToString()
I hope this helps (just another way to do it). It is along the same lines of Amessihel.
NOTE: if TimeOfDay is greater than 24 hrs. then it puts out EX: "1.00:05:09"
Dim dgvrRow As DataGridViewRow
Dim tsSum As TimeSpan
Dim tsTemp As TimeSpan
TimeSpan.TryParse("00:00:00", tsSum)
For Each row In datagridview3.rows
strTemp = row.Cells(2).Value.ToString
If strTemp <> String.Empty Then
tsTemp = DateTime.ParseExact(strTemp, "HH,mm,ss", Nothing).TimeOfDay
tsSum = tsSum.Add(tsTemp)
End If
Next
txtTotalTime.Text = tsSum.toString
Unfortunately, Sum() cannot handle a set of TimeSpan. So the trick here is:
To parse each entry invoking DateTime.ParseExact with a custom format (I assumed yours was h,m,s)
To convert them as "Ticks", a Long value.
To pass the Long values to Sum()
And finally to convert the result as a TimeSpan.
Below a working piece of code:
Dim ts As TimeSpan = New TimeSpan(
(From row As DataGridViewRow In DataGridView3.Rows
Where row.Cells(2).FormattedValue.ToString() <> String.Empty
Select DateTime.ParseExact(row.Cells(2).FormattedValue, "h,m,s", Nothing).TimeOfDay.Ticks
).Sum())
txtTotalTime.Text = ts.ToString
Note: Nothing is passed here as a format provider. Globalization.CultureInfo.InvariantCulture could also be passed with the same effect.

How to convert time in string format into datetime format in VB.Net

The following string was generated by this code:
myString = 12:44:44.6111472
myString = Date.Now.TimeOfDay.ToString
I want to add 16.1234567 seconds and the value of myString and assign the resulting value to a new string called myNewString.
Every function I have tried looses the 7 decimal places.
Is there another method I can use that doesn't require me to break apart the entire string value, modify the desired parts, account for carry's, then re-assemble?
If not, then so-be-it.
But, I would like think there is some method, and I'm just not finding it!
Thanks!
Datetime has some parsing functions that you can use. For example:
Dim mystring As String = "12:44:44.6111472"
Dim dt As System.DateTime = System.DateTime.Parse(mystring)
dt += New TimeSpan(16.1234567 * TimeSpan.TicksPerSecond)
mystring = dt.TimeOfDay.ToString()
'now mystring = "12:45:00.7346039"
Here's another approach similar to Ben J's without the use of timespan (which may make things look simpler):
Dim myString = Date.Now.TimeOfDay.ToString
' parse datetime string and add seconds
Dim myDate = DateTime.Parse(myString).AddSeconds(16.1234567)
' outputs 16.123000 so you still lose a few decimal points but not all 7,
' is this close enough precision for you?
Dim ts = String.Format("{0:N6}", (New TimeSpan(myDate.Ticks) - New TimeSpan(DateTime.Parse(myString).Ticks)).TotalSeconds)

how to get value by split in vb.net 2005

i have a database in one field like below 222-225. I try to make split to read that value for my function. Just simple function a=225 b=222 then total=(a-b)+1. here my code
Dgv.CellClick
'Dim x As Boolean
Dim a As Double
Dim total As Double
a = CDbl(Dgv.Item(8, Dgv.CurrentRow.Index).Value)
Split(a, "-")
total = (a) - (a)
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total
My problem is this doesn't work. I can't get the value that I split. Any idea how to solve this problem?
note: I use VB.NET 2005
If you want total=(a-b)+1 .. That should be
dim b = a.Split("-")
total = val(b(1)) - val(b(2)) + 1
may be this can help. try this...
Dim a As String
a = ""
Dim x As String
Dim total As Double
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString
Dim ary() As String
x = a
ary = x.Split("-")
total = CInt(ary(1)) - CInt(ary(0))
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total
Like others have said, Split() returns a String array, like this:
Dim SplitValue() As String = Split(a, "-")
total = (CType(SplitValue(1), Double) - CType(SplitValue(0), Double)) + 1
If I read your question correctly, the value you're looking for is 222-225, and that value is located in the specified cell of Dgv (which I'm guessing is a DataGridView). If my understanding is correct, there are a couple of things going on.
First, I'm not sure why you're trying to convert that value to a double with the following line of code:
a = CDbl(Dgv.Item(8, Dgv.CurrentRow.Index).Value)
The Item property of a DataGridView holds a DataGridViewCell, and the Value property of the DataGridViewCell returns an Object. Trying to convert 222-225 to a double will, I believe, fail (though since this is VB.NET, it's possible it won't depending on the options you set - I'm not as familiar with VB.NET as I am with C#).
Even if it does successfully work (I'm not sure what the output would be), Split expects a string. I would change that line of code to the following:
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString()
Now you have a string that you can use Split on. The Split you have in your posted code appears to be the Visual Basic (pre-.NET) Split method Split Function (Visual Basic). As others have mentioned, Split returns an array of strings based on the delimiter. In your code, you don't assign the result of Split to anything, so you have no way to get the values.
I would recommend using the .NET version of Split (String.Split Method) - there are several ways you can call String.Split, but for purposes of your code I'd use it like this:
Dim splits As String() = a.Split(New Char() { "-" })
Where a is the string value from the selected DataGridViewCell above. This will give you a 2-element array:
splits(0) = "222"
splits(1) = "225"
The final part is your formula. Since you have strings, you'll need to convert them to a numeric data type:
total = (CDbl(splits(1)) - CDbl(splits(0))) + 1
Which becomes (225 - 222) + 1 = 4.
Putting it altogether it would look something like this:
Dim a As String
Dim total As Double
Dim splits() As String
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString()
splits = a.Split(New Char() { "-" })
total = (CDbl(splits(1)) - CDbl(splits(0))) + 1
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total
Split returns an array. something like this. VB.Net is not my primary language but this should help.
dim arr = a.Split(New Char (){"-"})
total = ctype(arr(0), double) - ctype(arr(1),double)
Try this:
Dim aux() As String = a.Split("-"c)
total = CDbl(aux(0)) - CDbl(aux(1)) + 1
Dim a As string
Dim x As String
Dim total As Double
a = Dgv.Item(8, Dgv.CurrentRow.Index).Value
Dim ary() As String
x = a
ary() = x.Split("-")
total = CInt(ary(1)) - CInt(ary(0))
Dgv.Item(9, Dgv.CurrentRow.Index).Value = total

Vb.net Milliseconds Format

I Got This String:
00:00:59,950
lets say that i want :00:00:59,950 + 100
then the string look like:
00:01:00,050
there is a function that can do it?
You can use the TimeSpan type to handle this:
Dim ci = CultureInfo.InvariantCulture
Dim original As TimeSpan = TimeSpan.ParseExact("00:00:59,950", "hh\:mm\:ss\,fff", ci)
Dim difference As TimeSpan = TimeSpan.FromMilliseconds(100)
Dim final = original + difference
Dim output as String = final.ToString("hh\:mm\:ss\,fff", ci)
Try this:
Dim dateFormat As String = "hh:mm:ss.fffffff"
Dim date1 As Date = #00:00:59,950"
date1.AddMilliseconds(100)
UPDATE:
I must've been more tired than I realized yesterday, I apologize for that.. This should do better:
Dim sTime As String = "00:00:59.950"
Dim dOffset As DateTimeOffset = DateTimeOffset.Parse(sTime)
dOffset = dOffset.AddMilliseconds(100)
Dim sDisplayTime As String = dOffset.ToString("HH:mm:ss.fff tt")
There you'll get the milliseconds in the format you stated in your question.