Conversion from date string to datetime C#

Asked

Viewed 830 times

6

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

Obg.

2 answers

7


You can use the method TryParse(...) 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 variable resultado indicates whether the conversation was successful or not.

Relative to the crop used for the conversion

Please note that by default the culture used to convert the string is the crop of the machine where the code runs. If you need to indicate another crop (for example en):

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.)

-1

I managed to solve a problem similar to:

String dataString = 31/12/2000;

DateTime dataEmDateTime = DateTime.ParseExact(dataString,"dd/MM/yyyy", CultureInfo.CreateSpecificCulture("pt-BR"));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.