168

I have a datetime coming back from an XML file in the format:

20080916 11:02

as in

yyyymm hh:ss

How can I get the datetime.parse function to pick up on this? Ie parse it without erroring?

starball
  • 20,030
  • 7
  • 43
  • 238
anonym0use
  • 2,936
  • 4
  • 25
  • 26

2 Answers2

301
DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

S. Baggy
  • 950
  • 10
  • 21
Blair Conrad
  • 233,004
  • 25
  • 132
  • 111
  • Also: standard Xml has it's own very specific DateTime format, and the .Net Xml tools should be able to read it. – Joel Coehoorn Dec 04 '08 at 16:37
  • In this case it works ok with last parameter as null but for anyone who finds this CultureInfo.InvariantCulture otherwise you can get problems if your datetime is something like "1823/01/01". – Todilo Sep 03 '13 at 07:16
  • @JoelCoehoorn `standard XML specific DateTime format` ? – Kiquenet Jul 27 '18 at 10:02
18

Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:

DateTime dt = DateTime.MinValue;

DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);
Mitat Koyuncu
  • 928
  • 8
  • 20
bert
  • 321
  • 2
  • 3