Index and length should refer to a location within the sequence - vb.net

I need to break a variable to get the value of the database. Today my full return would be "2017-09-15T14: 01: 46" I only need 2017-09-15 and 14:01, I tried to do
.Substring (0.10) for the date and worked, already for the time I tried Substring (11,16) and the error that is in the title of the question occurs.

Assuming you always have the capital T in your result string
dim xValue as string = "2017-09-15T14: 01: 46"
dim xStr() as string = xValue.split("T")
dim xDate as string = ""
dim xTime as string = ""
if xstr.count>0 then
xDate = xStr(0)
xTime = xStr(1)
end if
or
dim xValue as string = "2017-09-15T14: 01: 46"
dim xDate as string = strings.left(xValue, 10)
dim xTime as string = strings.mid(xValue, 12)

So with VB.NET, you can use the DateTime method. From the DateTime, you can do something like DateTime.Date or DateTime.ToShortDateString for just the date and DateTime.ToShortTimeString for the time.

Your arguments to the function Substring are wrong.
The second argument to the function Substring (in your case 16) needs to be the amount of letters that the function will return and NOT the index it needs to end in.
It will work with something like Substring(11, 5), where the 5 is the length of the returned substring.
Dim temp_date As String = "2017-09-15T14: 01: 46"
Dim main_date As String = temp_date.Substring(0, 10)
Dim main_time As String = temp_date.Substring(11, 6)
OR
a better approach using the datetime object proposed by AustinS90 (this will support alot of time formatted strings):
Dim temp_date As DateTime = DateTime.Parse("2017-09-15T14: 01: 46")
Dim main_date As String = temp_date.Year() & "-" & temp_date.Month() & "-" & temp_date.Day
Dim main_time As String = temp_date.Hour & ":" & temp_date.Minute

Related

Index and length must refer to a location within the string." & vbCrLf & "Parameter name: length vb.net

Public Sub Main(temp As String)
Dim AccNo As String = temp.Substring(0, 18)
Dim Identifier As String = temp.Substring(36, 46)
Dim Expected As String = temp.Substring(45, 98)
Dim Received As String = temp.Substring(100, 105)
Dim Length As String = temp.Length.ToString
lbLength.Text = Length.ToString
lbAcc.Text = AccNo.ToString
lbIdentifier.Text = Identifier.ToString
lbExpected.Text = Expected.ToString
lbReceived.Text = Received.ToString
End Sub
I'm trying to extract a section from a String line. It's working correctly first two times but then it generates
Index and length must refer to a location within the string." & vbCrLf & "Parameter name: length vb.net"
Please help me to solve this.
At the beginning of your Sub check the length of the temp string.
Dim temp As String = ""
If temp.Length < 205 Then
MessageBox.Show("String is too short to process")
Exit Sub
End If
Substring(StartPosition,length) length is number of characters from starting position.
If you want to do it like Substring(start_position,end_position) end position has to be replaced with (98-45), because end-start=length

Strange Date Parsing Results

I am trying to make a small helper app to assist in reading SCCM logs. Parsing the dates has been pretty straightforward until I get to the timezone offset. It is usually in the form of "+???". literal example: "11-01-2016 11:44:25.630+480"
DateTime.parse() handles this well most of the time. But occasionally I run into a time stamp that throws an exception. I cannot figure out why. This is where I need help. See example code below:
Dim dateA As DateTime = Nothing
Dim dateB As DateTime = Nothing
Dim dateStr_A As String = "11-07-2016 16:43:51.541+600"
Dim dateStr_B As String = "11-01-2016 11:44:25.630+480"
dateA = DateTime.Parse(dateStr_A)
dateB = DateTime.Parse(dateStr_B)
MsgBox(dateA.ToString & vbCrLf & dateB.ToString)
IF run it would seem dateStr_B is an invalid time stamp? Why is this? I've tried to figure out how to handle the +480 using the 'zzz' using .ParseExact() format as shown here Date Formatting MSDN
Am I missing something with the timezone offset? I've searched high and low but these SCCM logs seem to use a non standard way of representing the offset. Any insight would be greatly appreciated
The problem is that +480 is indeed an invalid offset. The format of the offset from UTC (as produced when using the "zzz" Custom Format Specifier) is hours and minutes. +600 is 6 hours and 0 minutes ahead of UTC, which is valid. +480 would be 4 hours and 80 minutes ahead of UTC, which is invalid as the number of minutes can't be more than 59.
If you have some external source of date and time strings that uses an offset that is simply a number of minutes (i.e. +600 means 10 hours and +480 means 8 hours), you will need to adjust the offset before using DateTime.Parse or DateTime.ParseExact.
[Edit]
The following function takes a timestamp with a positive or negative offset (of any number of digits) in minutes, and returns a DateTime. It throws an ArgumentException if the timestamp is not in a valid format.
Public Function DateTimeFromSCCM(ByVal ts As String) As DateTime
Dim pos As Integer = ts.LastIndexOfAny({"+"c, "-"c})
If pos < 0 Then Throw New ArgumentException("Timestamp must contain a timezone offset", "ts")
Dim offset As Integer
If Not Integer.TryParse(ts.Substring(pos + 1), offset) Then
Throw New ArgumentException("Timezone offset is not numeric", "ts")
End If
Dim hours As Integer = offset \ 60
Dim minutes As Integer = offset Mod 60
Dim timestamp As String = ts.Substring(0, pos + 1) & hours.ToString & minutes.ToString("00")
Dim result As DateTime
If Not DateTime.TryParse(timestamp, result) Then
Throw New ArgumentException("Invalid timestamp", "ts")
End If
Return result
End Function
Thank you for the insight. I had a feeling I would need to handle this manually. I just wanted to make sure I wasn't missing something simple in the process. My knowledge of the date and time formatting is a bit lacking.
As such, I have altered my code so that it handles the offset. Granted I will have to add some more input validation in the final product.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dateA As DateTime = Nothing
Dim dateB As DateTime = Nothing
Dim dateStr_A As String = correctOffset("11-07-2016 16:43:51.541+600")
Dim dateStr_B As String = correctOffset("11-07-2016 16:43:51.541+480")
dateA = DateTime.Parse(dateStr_A)
dateB = DateTime.Parse(dateStr_B)
MsgBox(dateA.ToString & vbCrLf & dateB.ToString)
End Sub
Public Function correctOffset(ByVal ts As String)
Dim offset As Integer = CInt(ts.Substring(ts.Length - 3))
Dim offHour As Integer = offset / 60
Dim offMin As Integer = offset - (offHour * 60)
Dim strhour As String = Nothing
Dim strmin As String = Nothing
If offHour <= 9 Then
strhour = "0" & CStr(offHour)
Else
strhour = CStr(offHour)
End If
If offMin <= 9 Then
strmin = "0" & CStr(offMin)
Else
strmin = CStr(offMin)
End If
Return ts.Substring(0, ts.Length - 3) & strhour & ":" & strmin
End Function

Input string was not in a correct format while adding string to integer

I have a code like this :
Dim mincatval As String
Dim strarr() As String = dr1(0).ToString().Split(New Char() {"-"c})
Dim i As String
i = (Integer.Parse(strarr(0)) + 1)
mincatval = i
my dr(1) value is L1 i want to add 1,so i want the out put L2,but i am getting error like this :Input string was not in a correct format.
Supposing that strarr(0) is the word "L1" and you want it to become "L2" then you need to isolate the numeric part from the text part and then rebuild the string taking the first part of strarr and the incremented value
Dim mincatval As String
Dim strarr() As String = dr1(0).ToString().Split(New Char() {"-"c})
Dim i As String
Dim itShouldBeAnumber = strarr(0).Substring(1)
if Int32.TryParse(itShouldBeAnumber, i) Then
mincatval = strarr(0).Substring(0,1) & (i + 1)
else
MessageBox.Show("Not a valid number from position 1 of " & strarr(0))
End if
Of course this solution assumes that your string is Always composed of an initial letter followed by a numeric value that could be interpreted as an integer

Vb.net - Split String and convert to DateTime

I have 1 datagridview named IncomingMailDGV.
Sample data on Contents Column:
R-1 temperature (6.25) rose above high bound SLTCR at Warehouse-1 at 27/07/15 13:40
R-2 temperature (6.62) rose above high bound SLTCR at Store at 27/07/15 13:42
R-3 temperature (6.31) rose above high bound SLTCR at Warehouse-2 at 27/07/15 13:45
Note: Some contents has three spaces on the last part of the message.
I want to get the date and time which is placed on the last part and convert it to this format: "M/dd/yyyy HH:mm tt"
I'm using below code but its not working:
Sub FilterAlert()
Try
Dim Dbcon As New OleDbConnection(connStr)
Dbcon.Open()
For x As Integer = 0 To IncomingMailDGV.Rows.Count - 1
Dim line2 As String = IncomingMailDGV.Rows(x).Cells("Contents").Value.ToString
Dim separators() As String = {",", " ", "(", ")"}
Dim length As Integer = line2.Length
Dim alertdatetime As String
Dim alertdate_time As String
data2 = line2.Split(separators, StringSplitOptions.RemoveEmptyEntries)
alertdate_time = line2.Substring(length - 14, 14)
Dim alertstring = alertdate_time.Split(separators, StringSplitOptions.RemoveEmptyEntries)
alertdatetime = alertstring(0)
alertdatetime = DateTime.ParseExact(alertdatetime, "dd/MM/yyHH:mm", Nothing)
console.writeline (alertdatetime)
Next
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
Update: Some cells on Contents Column are empty.
If you mean that there may be more than one space between the date and the time, then you can just take the last 14 characters from the string. The following code assumes that the date and time are always preceded by " at ". It's not clear what you want to do if the string is not in the correct format, this code simply ignores invalid strings.
Note that DateTime doesn't have a format, it's just numbers. You can use DateTime.ToString to output the date and time in whatever format you want.
This code is intended to replace everything inside the For loop.
Dim line2 As String = IncomingMailDGV.Rows(x).Cells("Contents").Value.ToString
Dim pos As Integer = line2.LastIndexOf(" at ")
If pos < 0 Then Continue For
Dim alertstring() As String = line2.Substring(pos + 4).Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
If alertstring.length <> 2 Then Continue For
Dim alertdatetime As DateTime
If Not DateTime.TryParseExact(alertstring(0) & alertstring(1), "dd/MM/yyHH:mm", _
System.Globalization.CultureInfo.InvariantCulture, Nothing, alertdatetime) Then Continue For
Console.WriteLine(alertdatetime.ToString("M/dd/yyyy HH:mm tt"))

Checking Row by Row in a report

With reference to this question,
Changing Row Colour according to condition
I got familiar with Conditional formatting. However I still face this problem.
I am using this code to convert time into Time in Minutes.
Dim TestString As String
TestString = Me.Duration
Dim TestArray() As String
TestArray = Split(TestString, ":")
Dim Hours As String
Dim Minutes As String
Dim Seconds As String
Dim HoursMinutes As Integer
Dim MinutesMinutes As Integer
Dim SecondsMinutes As Integer
Hours = TestArray(0)
Minutes = TestArray(1)
Seconds = TestArray(2)
HoursMinutes = CInt(TestArray(0)) * 60
MinutesMinutes = CInt(TestArray(1))
SecondsMinutes = CInt(TestArray(2)) / 60
Dim TimeInMinutes As Integer
TimeInMinutes = HoursMinutes + MinutesMinutes + SecondsMinutes
Me.Duration = TimeInMinutes
However, for some reason this is not working.
Have you any ideas how can I do this for seperate rows?
Thanks in advance
ADD:
I tried creating a field for Minutes, the problem is that they will get all the same number.
the below code has a String variable called dateTime which stores the current date and time in this format: 27/08/2013 10:55:52
The dateTime String is getting split into a Variant arr array
Split(dateTime, Chr(32))(1) returns the time 10:55:52 part of the dateTime variable
then Split(Split(dateTime, Chr(32))(1), ":") splits the time into 3 numbers using : (colon) as delimiter
So you end up with with arr holding # of hrs, # of minutes, # of seconds.
The CLng((arr(0) * 60) + arr(1) + (arr(2) / 60)) returns an Integer/Long representation of the calculated time value
Stick the below sub in a fresh module and run it
Sub Convert()
Dim dateTime As String
dateTime = now
Dim arr
arr = Split(Split(dateTime, Chr(32))(1), ":")
MsgBox "The time " & Split(dateTime, Chr(32))(1) & vbCrLf & _
" as Integer is equal to " & CLng((arr(0) * 60) + arr(1) + (arr(2) / 60))
End Sub