Tiago Turella
Tiago Turella

Reputation: 39

How to convert textbox year date value to check if it has only 2 digits?

The problem that I have is related to only being possible to insert 2 digit's on the field year and I was wondering if it was possible to have a string with a value 2017 and only inserting 17 when I press a button.

I have tried to use the CONTAINS property to check if it only has numbers, but now I'm kind of stuck.

Upvotes: 0

Views: 618

Answers (3)

Nick
Nick

Reputation: 886

Assuming your user enters a date like this: 01/01/2017, into the textbox:

dim dateFromTextbox = yourTextbox.Text ' ==> 01/01/2017
dim lastTwoDigits = Right(dateFromTextbox, 2)  ' ==> 17

Upvotes: 1

Ulug Toprak
Ulug Toprak

Reputation: 1222

You can use a string/substring concept;

Module DateSplit
    Sub Main()
      Dim literal As String = "2017"
      Dim substring As String = literal.Substring(2)
      Console.WriteLine("Substring: {0}", substring)
   End Sub
End Module

I did not test this code but should output 17

Another approach would be casting your date as a string and create a char array, then you can have access to the element and convert them back to numbers if you like

Dim dateToSplit As Integer = 2017
Dim strDate As String = dateToSplit.ToString()

Dim charArr() AS Char = strDate.ToCharArray()

Upvotes: 1

user7907954
user7907954

Reputation:

You could use regex.

Private Function returnLastTwo(input As Integer) As Integer
    Dim matchYearString As String = "(?:(\d\d)(?:(\d\d))?)"
    Dim output As Integer
    If CStr(input).Length = 4 Then
        output = Text.RegularExpressions.Regex.Match(CStr(input), matchYearString).Groups(2).Value
    ElseIf CStr(input).Length = 2 Then
        output = Text.RegularExpressions.Regex.Match(CStr(input), matchYearString).Groups(1).Value
    Else
        Throw New Exception("Check input")
    End If
    Return output
End Function

Upvotes: 1

Related Questions