How can I parse a string that lacks delimiters to a DateTime using c#?

Hey. I have, somehow, this string available “20100205 162206”. This is a date and time without any delimiter char.

I need this back as a DateTime in C#. What is the best way?

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

Use one of the overloads of DateTime.ParseExact and specify a custom DateTime format string:

DateTime.ParseExact(
      "20100205 162206",
      "yyyyMMdd HHmmss",
      CultureInfo.InvariantCulture);

What this does is specify an exact format string for your input. (Namely “year-month-day hour-minute-second” without the dashes.)

If your input will always come in in one way, you are safest to use the ParseExact function, because, if you recieve bad data, it allows you to “fail early” rather than operating on inconsistent data.


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x