在CV StreamReader(C#)期间将字符串转换为DateTime

时间:2019-06-28 07:04:57

标签: c# date datetime type-conversion datetime-conversion

StreamReader 期间,我无法将字符串转换为日期:

string line;
StreamReader sr = new StreamReader(file.ToString());
while ((line = sr.ReadLine()) != null)
{
 string col13 = line.Split(',')[13]; //"22/06/2014 00:00:00"    
}

我尝试了以下代码,但出现错误:

DateTime x = DateTime.Parse(col13); 
//or
DateTime y = Convert.ToDateTime(col13);
//System.FormatException: 'String was not recognized as a valid DateTime.'

CultureInfo culture = new CultureInfo("en-US");
DateTime tempDate = Convert.ToDateTime(col13, culture);
//System.FormatException: 'String was not recognized as a valid DateTime.'

DateTime y = DateTime.ParseExact(col13, "dd/mm/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
//System.FormatException: 'DateTime pattern 'm' appears more than once with different values.'

1 个答案:

答案 0 :(得分:2)

DateTime.ParseExact()格式,而不是mm使用MM

从MSDN,

  

“ MM”自定义格式说明符将月份表示为来自   01至12

  

“ mm”自定义格式说明符将分钟表示为数字   从00到59。

因此,您的DateTime.ParseExact()

DateTime y = DateTime.ParseExact(col13, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
                                          //^^      ^^ This needs to update