0

I need to format times to be like this:

Inputs to the function look like

Input        Output
01:20        0120
0120         0120
01:20:23     0120
120          0120
01           0100
1            0100

We used to use VB6.Format, but cannot any longer. How would I use something such as String.Format to replace this code?

We would use something like this previously

TimeFormatVariable = VB6.Format(OriginalTimeInput, "hhnn")
LittleBobbyTables - Au Revoir
  • 32,008
  • 25
  • 109
  • 114
user2178477
  • 47
  • 2
  • 11
  • Your input looks like bad strings. How do you know `01` is one hour and not one minute? – LarsTech Jul 10 '13 at 19:56
  • possible duplicate of [Is there a way to programmatically convert VB6 Formatting strings to .NET Formatting strings?](http://stackoverflow.com/questions/4072490/is-there-a-way-to-programmatically-convert-vb6-formatting-strings-to-net-format) – Hans Passant Jul 10 '13 at 20:38
  • In VB6 format doesn't work that way. For instance "0120" produces "0000" – tinstaafl Jul 11 '13 at 02:30

2 Answers2

1

Assuming your OriginalTimeInput is either DateTime or Date format:

OriginalTimeInput.ToString("hhmm")

Should do it.

0

Here's a simple function that will take a string formatted like any of your inputs and the format you specify, and returns a string formatted like your outputs:

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

This does simple validating as well. It checks for proper time format and if not, if all characters are digits

Your statement would look like this:

`TimeFormatVariable = FormatTime(OriginalTimeInput, "hhmm")

tinstaafl
  • 6,908
  • 2
  • 15
  • 22