如何将字符串转换为DateTime [英] How to convert a string to DateTime
问题描述
我的系统日期格式为"dd.MM.yyyy".
我想将字符串"15.05.2012"转换为DateTime.
当我使用Convert.ToDateTime("15.05.2012")进行转换时,它显示一条错误消息无法将字符串转换为....".但是我可以将字符串"05.15.2012"转换为DateTime.
我怎样才能做到这一点?请帮忙
My system date format is ''dd.MM.yyyy''.
I want convert the string "15.05.2012" to DateTime.
When I convert this using Convert.ToDateTime("15.05.2012"), it is showing an error message ''String cannot be convert to.....''. But I could convert the string "05.15.2012" to DateTime.
How can I do this? pls help
推荐答案
您基本上有两个选择.
DateTime.Parse()
和DateTime.ParseExact()
.
第一个在语法方面非常宽容,并且会以许多不同的格式解析日期.这对于可能以不同格式出现的用户输入很有用.
ParseExact将允许您指定要用于解析的日期字符串的确切格式.如果您的字符串始终采用相同的格式,则最好使用此格式.这样,您可以轻松地检测到与预期数据的任何偏差.
请参考:
将字符串转换为DateTime [ DateTime.Parse方法(字符串) [ Convert.ToDateTime方法(字符串) [将字符串转换为DateTime对象 [ ^ ]
You have basically two options for this.
DateTime.Parse()
andDateTime.ParseExact()
.
The first is very forgiving in terms of syntax and will parse dates in many different formats. It is good for user input which may come in different formats.
ParseExact will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. This way, you can easily detect any deviations from the expected data.
Please refer:
Convert a String to a DateTime [^]
DateTime.Parse Method (String)[^]
Convert.ToDateTime Method (String)[^]
Similar discussion:
Convert String to DateTime Object [^]
Try This
string myDateTimeValue = "2/16/1992 12:15:12";
DateTime myDateTime = DateTime.Parse(myDateTimeValue);
或
你可以扔这个链接
http://www.ezineasp.net/post/C-Convert-String-to- DateTime.aspx [ ^ ]
http://www.dotnetspider.com/forum/4879-How-convert-string-datetime-datetime-format-using-C.aspx [
or
You can go threw this link
http://www.ezineasp.net/post/C-Convert-String-to-DateTime.aspx[^]
http://www.dotnetspider.com/forum/4879-How-convert-string-datetime-datetime-format-using-C.aspx[^]
DateTime dateTime = DateTime.ParseExact("15.05.2012", "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
这篇关于如何将字符串转换为DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!