Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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?

like image 693
Jango Avatar asked Feb 08 '10 17:02

Jango


People also ask

How to use TryParseExact in c#?

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.

What does DateTime parse do?

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.

Can we convert DateTime to string in C#?

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.

How do you check if the date is in dd mm yyyy format in C #?

Use DateTime. TryParseExact to try to parse it: string text = "02/25/2008"; DateTime parsed; bool valid = DateTime. TryParseExact(text, "MM/dd/yyyy", CultureInfo.


1 Answers

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.

like image 167
John Gietzen Avatar answered Sep 20 '22 14:09

John Gietzen