C# 字符串转换成日期
一、拼接字符串的形式
DateTime dt=Convert.ToDateTime("20220101".Substring(0,4)+"-"+"20220101".Substring(4,2)+"-"+"20220101".Substring(6,2))
二、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("2022/05/26", dtFormat);
四、DateTime.ParseExact()
string dateString = "20220526"; DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture); //或者 DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
五、DateTime.TryParse(string,out datetime)
https://docs.microsoft.com/zh-cn/dotnet/api/system.datetime.tryparse?view=net-6.0
DateTime.ParseExact
string str = "20220110"; IFormatProvider ifp = new CultureInfo("zh-CN", true); DateTime dt = DateTime.ParseExact(str, "yyyyMMdd", ifp); MessageBox.Show(dt.ToString("yyyy-MM-dd"));
DateTime.TryParseExact
string str = "20220110"; DateTime dt; IFormatProvider ifp = new CultureInfo("zh-CN", true); if (DateTime.TryParseExact(str, "yyyyMMdd", ifp, DateTimeStyles.None, out dt)) { MessageBox.Show(dt.ToString(("yyyy-MM-dd")); }
![](http://www.studyofnet.com/Codefan-Controls/OutliningIndicators/None.gif)