【问题标题】:String to DateTime convert during CV StreamReader (C#) [duplicate]在CV StreamReader(C#)期间将字符串转换为DateTime [重复]
【发布时间】:2019-06-28 07:04:57
【问题描述】:

我在 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.'

【问题讨论】:

  • dd/mm/yyyy -> 您是否打算在日期格式中包含分钟?还是您的意思是几个月 (MM)?
  • "dd/MM/yyyy HH:mm:ss",请注意M 月份和H0..23 范围)小时
  • 完美,谢谢,你可以把这个作为答案

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-12-05
    • 2013-03-12
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2018-10-19
    相关资源
    最近更新 更多