这是一个简单的函数,它将采用与您的任何输入和您指定的格式一样格式化的字符串,并返回与您的输出一样格式化的字符串:
Private Function FormatTime(Input As String, Format as String) As String
Dim TimeFormat As New DateTime
Dim GoodString As Boolean = DateTime.TryParse(Input, TimeFormat)
If Not GoodString Then
If Integer.TryParse(Input, vbNull) Then
If Input.Length > 2 Then
Input = Input.PadLeft(4, "0"c)
TimeFormat = New DateTime(Now.Year, Now.Month, Now.Day, Integer.Parse(Input.Substring(0, 2)), Integer.Parse(Input.Substring(2)), 0)
Else
TimeFormat = New DateTime(Now.Year, Now.Month, Now.Day, Integer.Parse(Input.PadLeft(2, "0"c).Substring(0, 2)), 0, 0)
End If
End If
End If
Return TimeFormat.ToString(Format)
End Function
这也可以进行简单的验证。它检查正确的时间格式,如果不是,是否所有字符都是数字
您的声明将如下所示:
`TimeFormatVariable = FormatTime(OriginalTimeInput, "hhmm")