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?
TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly.
The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.
The ToString() method of the DateTime class is used to convert a DateTime date object to string format. The method takes a date format string that specifies the required string representation.
Use DateTime. TryParseExact to try to parse it: string text = "02/25/2008"; DateTime parsed; bool valid = DateTime. TryParseExact(text, "MM/dd/yyyy", CultureInfo.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With