码迷,mamicode.com
首页 > Windows程序 > 详细

C#中将字符串转换成日期的方式

时间:2015-08-05 13:13:43      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:c#

一、拼接字符串的形式

 

DateTime dt=Convert.ToDateTime("20100101".Substring(0,4)+"-"+"20100101".Substring(4,2)+"-"+"20071107".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("2011/05/26", dtFormat);



四、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")来转换为特殊需求的格式,比较灵活方便。




参考资料:C#中字符串转换成日期   http://www.studyofnet.com/news/851.html

本文出自 “学习也休闲” 博客,请务必保留此出处http://studyofnet.blog.51cto.com/8142094/1681791

C#中将字符串转换成日期的方式

标签:c#

原文地址:http://studyofnet.blog.51cto.com/8142094/1681791

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!