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?
Cheers
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0