In this code item.date_time
looks like "2017-10-18T04:57:39.000Z". When I put this (or any other similar string) instead of item.date_time
- it works well. But despite the fact that item.date_time
is equal to strings like this - it calls System.FormatException when I use it.
static void Main(string[] args)
{
eventList = new List<CsvFile>();
StreamReader sr = new StreamReader("logs.csv");
string data = sr.ReadLine();
while (data != null)
{
string[] line = data.Split(',');
ReadString(line);
data = sr.ReadLine();
}
}
class CsvFile
{
public String date_time;
public DateTime datetime;
}
static void ReadString(String[] str)
{
CsvFile item = new CsvFile();
item.date_time = str[0];
item.datetime = DateTime.ParseExact(item.date_time, "yyyy-MM-ddTHH:mm:ss.000Z", CultureInfo.InvariantCulture);
eventList.Add(item);
}
I went through dozens of questions and answers about datetime issues today, but found nothing can solve this strange thing. Any ideas what is the problem with my code?
str[0] is equal
"\"2017-10-18T04:57:39.000Z\""
Your string has quotes around it (hence the \"
indicators). Trim those before parsing:
item.date_time = str[0].Trim('"');
item.datetime = DateTime.ParseExact(item.date_time, "yyyy-MM-ddTHH:mm:ss.000Z", CultureInfo.InvariantCulture);
You might consider using TryParseExact
so you can determine if the parse was successful and show a better error message (like which record you're on, what the input value is, etc.) rather than throwing an exception.
Another alternative is to use a CSV parsing library that can handle both the quotes around values and the date/time parsing for you.