views:

243

answers:

4

Hi. i'm amol kadam,I want to know how to split string in two part.My string is in Time format (12:12).& I want to seperate this in hour & minute format.the datatype for all variables are string. for hour variable used strTimeHr & for minute strTimeMin .I tried below code but their was a exception "Index and length must refer to a location within the string. Parameter name: length"

                If Not (objDS.Tables(0).Rows(0)("TimeOfAccident") Is Nothing Or objDS.Tables(0).Rows(0)("TimeOfAccident") Is System.DBNull.Value) Then
                    strTime = objDS.Tables(0).Rows(0)("TimeOfAccident") 'strTime taking value 12:12
                    index = strTime.IndexOf(":")                        'index taking value 2  
                    lastIndex = strTime.Length                          'Lastindex taking value 5   

                    strTimeHr = strTime.Substring(0, index)               'strTime taking value 12 correctly
     strTimeMin = strTime.Substring(index + 1, lastIndex)   'BUT HERE IS PROBLEM OCCURE strTimeMin Doesn't taking any value
                    Me.NumUpDwHr.Text = strTimeHr
                    Me.NumUpDwMin.Text = strTimeMin
                End If
A: 

Try something like (String.Split Method )

Dim str As String = "12:13"
Dim strHr = str.Split(":")(0)
Dim strMin = str.Split(":")(1)
astander
A: 
Stephen Wrighton
amol kadam
thanks...It's working
amol kadam
+1  A: 
string s = "12:13";
DateTime dt = DateTime.Parse(s);

Console.Write(dt.Hour + " " + dt.Minute);
Raj Kaimal
A: 

Is the datatype of the column "TimeOfAccident" a DateTime? If so, then the simplest solution would be something like:

'Using LINQ to convert the value to a nullable datetime.
Dim timeOfAccident As Nullable(Of DateTime) = dt.Rows(0).Field(Of Nullable(Of DateTime))("TimeOfAccident")

If timeOfAccident.HasValue Then
    Me.NumUpDwHr.Text = timeOfAccident.Hour
    Me.NumUpDwMin.Text = timeOfAccident.Minute
End If

If the column "TimeOfAccident" is a string, then you can do something like:

Dim timeOfAccidentString As String = dt.Rows(0).Field(String)("TimeOfAccident")

If Not String.IsNullOrEmpty(timeOfAccidentString) Then
    Dim accidentTime As DateTime = DateTime.Parse(timeOfAccidentString)
    Me.NumUpDwHr.Text = timeOfAccident.Hour
    Me.NumUpDwMin.Text = timeOfAccident.Minute
End If
Thomas