Failing to parse date in yyyyMMdd Hmm format using DateTime.TryParseExact()

I am getting my date time in a format like "20170317 630" which means 17 March 2017 6:30 am

Here is the code block I am trying, but it is failing.

var str = "20170317 0630";
var formatedTime = "yyyyMMdd Hmm";
DateTime etaDate;
if (!DateTime.TryParseExact(str,formatedTime, CultureInfo.InvariantCulture, DateTimeStyles.None, out etaDate))  //formatedTime, CultureInfo.InvariantCulture, DateTimeStyles.None
{
    Console.WriteLine("Date conversion failed " +  etaDate);
}

Console.WriteLine("Date conversion passed "+etaDate);

Passing for: 20170317 0630

Failing for: 20170317 630

Please help me with this.

Jon Skeet
people
quotationmark

I'm not entirely surprised it's failing to parse that - I suspect it's greedily parsing the "63" and deeming that to be an invalid hour number.

We have exactly the same problem in Noda Time - and I don't intend to fix it. Making this work would be a huge amount of effort, and quite possibly reduce the performance for more sensible formats.

I would strongly suggest moving to a more sensible format, e.g. one of

  • H:mm to remove the pseudo-ambiguity
  • HHmm to make it all clearer
  • HH:mm even better, IMO - preferrably with hyphens for date parts, so yyyy-MM-dd HH:mm

You can convert from one format to another by simply detecting the length of the string, as every other part of it is a fixed length. For example, to just move to using HHmm you can do:

if (str.Length == "yyyyMMdd Hmm".Length)
{
    str = str.Insert("yyyyMMdd ".Length, "0");
}

Then parse with yyyyMMdd HHmm format. If the length isn't right for either valid width, then it will fail to parse later anyway.

people

See more on this question at Stackoverflow