Newbie question: Substring2

rhcarpenter

Member
Licensed User
Longtime User
I'm not a Basic programmer. So forgive me if this is a stupid question.

I have written the following sub routine. I pass a date formatted as a string to the sub. The date string is formatted as mm/dd/yyyy. Inside the sub, I want to split out the mm, dd, yyyy components. I am using the SubString2 function to do this. The local variable sMonth is set correctly. But the next line where I try to set sDay throws the following exception:

An error has occurred in sub: main_validdate(B4A line: 92)
sday = ThisDate.Substring2(3,2)
java.lang.StringIndexOutOfBoundsException.

The sub is shown below. Any help will be appreciated.

Sub ValidDate(ThisDate As String) As Boolean
' Error if empty or length <> 10
If ThisDate.Trim.Length = 0 OR ThisDate.Length <> 10 Then
Return False
End If

' Error if 2nd or 5th char is <> "/"; string array is 0-based
Dim sLength As Int
sLength = ThisDate.Length
For i = 0 To sLength-1
Dim s As String
s = ThisDate.CharAt(i)
If (i <> 2) AND (i <> 5) AND (Not (IsNumber(ThisDate.CharAt(i)))) Then
Return False
End If
If ((i = 2) OR (i = 5)) AND (ThisDate.CharAt(i) <> "/") Then
Return False
End If
Next

Dim smonth As String
Dim sday As String
Dim syear As String

'This line works
smonth = ThisDate.SubString2(0,2)
'Exception is thrown when the next line is executed
sday = ThisDate.SubString2(3,2)
syear = ThisDate.SubString2(6,4)
End Sub
 

NJDude

Expert
Licensed User
Longtime User
You could do it faster using REGEX, check this out:
B4X:
Dim TheDate As String
Dim DateParsed() As String
            
TheDate = "04/01/2012"
            
DateParsed = Regex.Split("/", TheDate)
            
Msgbox("Month = " & DateParsed(0) & " - Day = " & DateParsed(1) & " - Year = " & DateParsed(2), "")
 
Upvote 0

klaus

Expert
Licensed User
Longtime User
Explanation why you got an error with SubString2:
Your code is:
B4X:
sday = ThisDate.SubString2(3,2)
syear = ThisDate.SubString2(6,4)
I think that in your mind the second parameter (2 or 4) is the number of characters to take into account.
But it should be:
B4X:
sday = ThisDate.SubString2(3,5)
syear = ThisDate.SubString2(6,10)
Because the second parameter is the EndIndex.
From the help file:
Returns a new string which is a substring of the original string.
The new string will include the character at BeginIndex and will extend to the character at EndIndex, not including the last character.
Best regards.
 
Upvote 0
Top