Conversion of date string to datetime C #

5

I have a method that will receive a string in the format "June 15, 2001", for example, which is equivalent to the date to be compared, I need to pass this string to a DateTime, how would I do this conversion?

    
asked by anonymous 09.06.2015 / 16:08

1 answer

6

You can use the TryParse(...) method of the structure DateTime :

DateTime data;
bool resultado = DateTime.TryParse("June 15, 2001", out data); // 6/15/2001 12:00:00 AM

The value of the resultado variable indicates whether the conversation was successful or not.

Relative to culture used for conversion

Note that by default the culture used to convert string is the culture of the machine where the code runs. If you need to indicate another culture (for example pt-PT):

DateTime data;
bool resultado = DateTime.TryParse("Junho 15, 2001", new CultureInfo("pt-PT"), DateTimeStyles.AdjustToUniversal, out data); // 

6/15/2001 12:00:00 AM

(See the first example in DotNetFiddle.)

(See the second example in DotNetFiddle.)

    
09.06.2015 / 16:14