Convert text to DateTime Three subtasks need to be executed: 1. Date and time strings in correct format. 2. Culture. The date and time representation formats of different regions are different, and the string format is different. 3. Specifies the conversion format, such as the converted DateTime, which may not have a time part.
Using Parse and TryParse transformations:
string dateInput = "Jan 1, 2009"; DateTime parsedDate = DateTime.Parse(dateInput); Console.WriteLine($"default zone{CultureInfo.CurrentCulture.Name}: "+parsedDate); // The description string format is en-us region DateTime parsedDate1 = DateTime.Parse(dateInput,new CultureInfo("en-us")); Console.WriteLine("Use en-us: " + parsedDate1); // name Case insensitive // public CultureInfo(string name); CultureInfo MyCultureInfo = new CultureInfo("de-DE"); string MyString = "12 Juni 2008"; DateTime MyDateTime = DateTime.Parse(MyString, MyCultureInfo); Console.WriteLine(MyDateTime);
DateTime dateTime; DateTime.TryParse("Jan 1, 2009",new CultureInfo("en-us"),DateTimeStyles.None,out dateTime);
ParseExact: can define string conversion format, can be standard format One of them can also be Custom format , but not all of them are successful. CultureInfo.InvariantCulture understand: https://www.cnblogs.com/GreenLeaves/p/6757917.html
string dateString, format; DateTime result; var provider = new CultureInfo("fr-FR"); dateString = "18/08/2015 06:30:15.006542"; // Custom format format = "dd/MM/yyyy HH:mm:ss.ffffff"; try { result = DateTime.ParseExact(dateString, format, provider); Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); } catch (FormatException) { Console.WriteLine("{0} is not in the correct format.", dateString); } // Parse date-only value with invariant culture. provider = CultureInfo.InvariantCulture; dateString = "06/15/2008"; format = "d"; try { result = DateTime.ParseExact(dateString, format, provider); Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); } catch (FormatException) { Console.WriteLine("{0} is not in the correct format.", dateString); }
See which cultureinfo is available. CultureInfo.GetCultures(CultureTypes.AllCultures).