简体   繁体   English

为什么datetime无法识别字符串?

[英]Why datetime can't recognise the string?

In this code item.date_time looks like "2017-10-18T04:57:39.000Z". 在此代码中, item.date_time看起来像“ 2017-10-18T04:57:39.000Z”。 When I put this (or any other similar string) instead of item.date_time - it works well. 当我把它(或任何其他类似的字符串)代替item.date_time -它工作得很好。 But despite the fact that item.date_time is equal to strings like this - it calls System.FormatException when I use it. 但是,尽管item.date_time等于这样的字符串-当我使用它时,它会调用System.FormatException。

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\\"" str [0]等于"\\"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. 您可能考虑使用TryParseExact以便可以确定解析是否成功并显示更好的错误消息(例如您在哪个记录上,输入值是什么等),而不是引发异常。

Another alternative is to use a CSV parsing library that can handle both the quotes around values and the date/time parsing for you. 另一种选择是使用CSV解析库,该库可以为您处理值周围的引号和日期/时间解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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