在 CV StreamReader (C#) 期间将字符串转换为 DateTime
String to DateTime convert during CV StreamReader (C#)
在 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.'
在 DateTime.ParseExact()
格式中,使用 MM
而不是 mm
来自 MSDN,
The "MM" custom format specifier represents the month as a number from
01 through 12
The "mm" custom format specifier represents the minute as a number
from 00 through 59.
所以,您的 DateTime.ParseExact()
将是
DateTime y = DateTime.ParseExact(col13, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
//^^ ^^ This needs to update
在 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.'
在 DateTime.ParseExact()
格式中,使用 MM
mm
来自 MSDN,
The "MM" custom format specifier represents the month as a number from 01 through 12
The "mm" custom format specifier represents the minute as a number from 00 through 59.
所以,您的 DateTime.ParseExact()
将是
DateTime y = DateTime.ParseExact(col13, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
//^^ ^^ This needs to update