当前位置:首页 > 技能相关 > C#与C++ > 正文内容

C# 字符串转换日期时间的方法

admin2年前 (2022-12-14)C#与C++5140 修订时间:2022-12-14 17:27:47

对于C#程序来说,类似于“20221214”、“20221214130506”这样类型的字符串,是无法单纯的使用DateTime.Pares() 这样的形式转换为日期类型的。

下面讲解具体转换如上类型字符串的方法,当然这是其中一种特例。

一、拼接字符串形式转换

DateTime d_t = Convert.ToDateTime("20221214".Substring(0,4)+"-"+"20221214".Substring(4,2)+"-"+"20221214".Substring(6,2));

以上方法过于笨重与繁琐;

二、Convert.ToDateTime(string)

使用该方法,string字符串格式有一定的要求,必须是yyyy-MM-dd hh:mm:ss 这样的类型;

string str = "2022-12-14 13:10:10";
DateTime d_t = Convert.ToDateTime(str);

三、Convert.ToDateTime(string, IFormatProvider)

第二种方法的拓展,可以指定具体的日期时间格式;

DateTime d_t;
DateTimeFormatInfo dtFormat = new System.GlobalizationDateTimeFormatInfo();
dtFormat.ShortDatePattern = "yyyy-MM-dd";
d_t = Convert.ToDateTime("2022-12-14", dtFormat);

四、DateTime.ParseExact()

第一个参数是需要转换成 DateTime格式的字符串,第二个参数format是转换后的样式,第三个参数为CultureInfo.CurrentCulture获取当前线程的区域信息中;

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

或者

DateTime.ParseExact("14/12/2022 12:01:02 PM","dd/MM/yyyy HH:mm:ss tt",System.Globalization.CultureInfo.InvariantCulture));

五、DateTime.TryParse(string,out datetime)

1、更多时候,会采用DateTime.TryParse(string,out datetime)方法,因为此方法有安全机制,当string内容不正确时,可以返回日期的最小值MinValue。并且可以通过返回的bool值判断转化是否成功。

而DateTime.ParseExact()需要按特定的格式来转换,对格式的要求比较严,如果string中不是日期内容,而类似“asdfasd”的字符串,则会出错。

2、用DateTime.TryParse(string,out datetime)转换后,得到的datetime可以用 datetime.ToString("ddd, MMM. dd")来转换为特殊需求的格式,比较灵活方便。

string s = "2016-09-08 18:38:50";
DateTime result;
bool result = DateTime.TryParse(s,out result);

接收一个可以转换为时间对象的字符串,接收一个DateTime类型的输出结果。返回一个bool类型的结果指示转换是否成功。 

 您阅读本篇文章共花了: 

免责声明
本站内容均为博客主本人日常使用记录的存档,如侵犯你的权益请联系:lifei@zaiheze.com 546262132@qq.com 沟通删除事宜。本站仅带访问端口形式使用,已杜绝搜索引擎爬取。

扫描二维码推送至手机访问。

版权声明:本文由LIFEI - blog发布,如需转载请注明出处。

本文链接:http://www.lifeiai.com/?id=263

分享给朋友:

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。