Tuesday, August 23, 2016

DateTime.ParseExact is throwing Format Exception when single H specified

Problem
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.


Solution

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');

            switch(input.Length)
            {
                case 2:
                    format = "HH";
                    break;
                case 4:
                    format = "HHmm";
                    break;
                case 6:
                    format = "HHmmss";
                    break;
                default:
                    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

There was an error in this gadget