E_T

导航

C# 字符串转为DateTime类型

Posted on 2017-11-10 13:41  E_T  阅读(3650)  评论(0编辑  收藏  举报

方法一: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);