C# 字符串转为DateTime类型

时间:2022-01-19 08:56:19

要领一:Convert.ToDateTime(string)

string格局有要求,,必需是yyyy-MM-dd hh:mm:ss

================================================

要领二:Convert.ToDateTime(string, IFormatProvider)

DateTime dt;

DateTimeFormatInfo dtFormat = new System.GlobalizationDateTimeFormatInfo();

dtFormat.ShortDatePattern = "yyyy/MM/dd";

dt = Convert.ToDateTime("2011/05/26", dtFormat);

================================================

要领二:DateTime.ParseExact()

string dateString = "20110526";

DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);

或者

DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);