简体   繁体   中英

Why datetime can't recognise the string?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM