字符串未被识别为有效的DateTime? [英] String was not recognized as a valid DateTime?
问题描述
我尝试字符串转换为日期时间
但每次我得到:
I try to convert string to datetime
but each time I get :
字符串未被识别为有效的DateTime。
String was not recognized as a valid DateTime.
code是:
string format = "dd/MM/yyyy";
obj.TransDate = DateTime.ParseExact(lbl_TransDate.Text.Split('/')[0] + "/" + lbl_TransDate.Text.Split('/')[1] + "/" + lbl_TransDate.Text.Split('/')[2], format, CultureInfo.InvariantCulture);
当我调试,我尝试分析它的日期是: 2012年12月4日
When I debug the date which I try to parse it is : 12/4/2012
推荐答案
所需的格式为:
string format = "dd/M/yyyy";
我不明白的事情,虽然,为什么拆分这些字符串连接在一起,因为你会得到同样的事情?
I don't understand a thing though, why split an concatenate the string, since you would obtain the same thing?
如果输入的是 2012年12月4日的,被拆分后的/的,你会得到12,4,2012,然后将它们连接起来回获得2012年12月4日。为什么这样?
If the input is 12/4/2012, after the split by '/', you'll get 12, 4, 2012 and then concatenate them back to obtain "12/4/2012". Why this?
另外,如果你真的需要那一刹那,您可以在存储到一个数组,所以你不需要拆的3倍:
Also, if you really need that split, you can store in into an array so you don't need to split it 3 times:
var splits = lbl_TransDate.Text.Split('/');
DateTime.ParseExact(splits[0] + "/" + splits[1] + "/" + splits[2], ...);
如果您不信任输入,劈叉阵列可能不是长度= 3,多的话,你可以使用的 DateTime.TryParseExact 的
If you don't trust the input, the splits array might not be of Length = 3, and more of it, you can use DateTime.TryParseExact
修改您可以使用多种格式的超载
因此,如果输入的可能的 2012年12月4日或12/04/2012 的,你可以给这两种格式
EDIT You can use the overload with multiple formats So if the input might be 12/4/2012 or 12/04/2012, you can give both formats
var formats = new[] {"dd/M/yyyy","dd/MM/yyyy"};
var date = DateTime.ParseExact("12/4/2012", formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeLocal);
这篇关于字符串未被识别为有效的DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!