c# 字符串转换日期
1.DateTime.TryParse和DateTime.TeyParseExact两个方法。
相同:转换失败返回false,可以指定转换的DateTime的Style和设置地点区域;
不同:TeyParseExact可以指定字符串输入的格式,不匹配将转换失败。
示例:

1 /// <summary> 2 /// 字符串转换成DateTime 3 /// </summary> 4 /// <param name="s">输入的字符串</param> 5 /// <returns>DateTime</returns> 6 private static DateTime ConvertToDateTimeExact(string s) 7 { 8 9 //仅支持例如2021/4/21 10:55:12这种格式,其余将转换失败 10 if (DateTime.TryParseExact(s.Trim(), "yyyy'/'M'/'d H':'mm':'ss", CultureInfo.InvariantCulture, 11 DateTimeStyles.None, out DateTime outDateTime)) 12 { 13 return outDateTime; 14 } 15 else 16 { 17 throw new Exception("输入的时间字符串格式不正确。"); 18 } 19 20 ////时间字符串转换格式 21 //string[] formats = new string[] 22 //{ 23 // "yyyy'/'M'/'d H':'mm':'ss", //示例 2021/4/21 10:55:12 24 // "yyyy'/'M'/'d", //示例 2021/4/21 25 // "H':'mm':'ss", //示例 10:55:12 26 // "yyyy'-'M'-'d H':'mm':'ss", //示例 2021-4-21 10:55:12 27 // "yyyy'-'M'-'d" //示例 2021-4-21 28 //}; 29 30 ////支持多种格式字符换 31 //if (DateTime.TryParseExact(s.Trim(), formats, CultureInfo.InvariantCulture, 32 // DateTimeStyles.None, out DateTime outDateTime)) 33 //{ 34 // return outDateTime; 35 //} 36 //else 37 //{ 38 // throw new Exception("输入的时间字符串格式不正确。"); 39 //} 40 } 41 /// <summary> 42 /// 字符串转换成DateTime,无法指定时间字符串格式 43 /// </summary> 44 /// <param name="s"></param> 45 /// <returns></returns> 46 private static DateTime ConvertToDateTime(string s) 47 { 48 if (DateTime.TryParse(s.Trim(), CultureInfo.InvariantCulture, 49 DateTimeStyles.None, out DateTime outDateTime)) 50 { 51 return outDateTime; 52 } 53 else 54 { 55 throw new Exception("输入的时间字符串格式不正确。"); 56 } 57 }