Tuesday, August 23, 2016

DateTime.ParseExact is throwing Format Exception when single H specified

DateTime.ParseExact("9", "H", CultureInfo.InvariantCulture) throws a FormatException.

It also throws the exception for the following cases:
1. "925", "Hmm"
2. "92525", "Hmmss"

Why? Because with a single "H", it tries to grab 1-2 characters. In the case of "925" it tries to grab "92" for the hour.


Let's say we want to allow the user to enter time in the following formats:

  • H
  • HH
  • Hmm
  • HHmm
  • Hmmss
  • HHmmss

What we can do is pad the string with a 0 to the left if the string length is odd. That is, if the time is in the formats H, Hmm, Hmmss, then we stick a 0 at the beginning and can simply use HH, HHmm, HHmmss.

For example

            string input = "925";
            string format = "";
            if (input.Length % 2 != 0)
                input = input.PadLeft(input.Length + 1, '0');

                case 2:
                    format = "HH";
                case 4:
                    format = "HHmm";
                case 6:
                    format = "HHmmss";
                    throw new ArgumentException("Time isn't within the expected lengths of 1-6");

            DateTime dt = DateTime.ParseExact(input, format, CultureInfo.InvariantCulture);

            //do stuff with dt

No comments:

Post a Comment