C #: convert date and time from a string with a different format

If my line is 01/26/2011 00:14:00 but my computer sets the format to United State (AM: PM) How to convert my line to Datetime? I try Convert.ToDateTime(), but it causes an error.

+3
source share
3 answers

As others have said, you can use DateTime.TryParseExact, but you also have a European culture format in your date. This may not prevent you from trying to use this to perform the conversion:

CultureInfo enGB = new CultureInfo("en-GB"); 
string dateString;
DateTime dateValue;

// Parse date with no style flags.
dateString = "26/01/2011 00:14:00";
DateTime.TryParseExact(dateString, "g", enGB, DateTimeStyles.None, out dateValue);
+6
source

DateTime.ParseExact DateTime.TryParseExact. datetime, , .

, "dd/mm/yyyy HH: MM: ss"

+6

I use DateTime.Tryparse - this way you can easily catch and handle the failure:

http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx

0
source

Source: https://habr.com/ru/post/1787757/


All Articles