Easy way to format a string to hh:mm format

Since the input will always be between 1 and 4 characters, perhaps you can check whether the input length is odd or even to determine if the parsed value starts with a “0” or not, and the rest is just padding 0’s to the right – something like this:

string ParseTime(string input)
{
    bool odd = (input.Length % 2 > 0);
    var result = (odd ? "0" : "") + input.PadRight(odd ? 3 : 4, '0');   
    return result.Insert(2, ":");
}

Leave a Comment