简体   繁体   English

为什么 DateTime.TryParseExact 不起作用?

[英]Why DateTime.TryParseExact is not working?

I am reading date from Excel and stored it in a variable In_Date , formats with which the date is to be compared is stored in Valid_Date_Formats我正在从 Excel 读取日期并将其存储在变量In_Date中,与日期进行比较的格式存储在Valid_Date_Formats

In_Date = "08/01/2020 00:00:00" In_Date = "08/01/2020 00:00:00"

Valid_Date_Formats is an array which stores multiple date formats. Valid_Date_Formats是一个存储多种日期格式的数组。

在此处输入图像描述

I am checking the format in if condition but it always fails.我正在检查 if 条件中的格式,但它总是失败。

If(DateTime.TryParseExact(In_Date, Valid_Date_Formats,
    System.Globalization.CultureInfo.InvariantCulture,
    System.Globalization.DateTimeStyles.None,
    DateTime_PlaceHolder))

What am I doing wrong here.我在这里做错了什么。

The input string has the following format: dd/MM/yyyy HH:mm:ss , which is missing from Valid_Date_Formats .输入字符串具有以下格式: dd/MM/yyyy HH:mm:ssValid_Date_Formats中缺少该格式。 (I'm assuming the 08 here is the day, because all your other formats start with the date part.) (我假设这里的08是这一天,因为所有其他格式都以日期部分开头。)

The following returns the correct date:以下返回正确的日期:

DateTime.ParseExact("08/01/2020 00:00:00", new[] { "dd/MM/yyyy HH:mm:ss" }, CultureInfo.InvariantCulture, DateTimeStyles.None)

In response to your comment: I'm not aware of a built-in method that would tell you which exact format string was used.回应您的评论:我不知道有一个内置方法可以告诉您使用了哪种确切的格式字符串。 If you really need to find out, I guess you could traverse the formats until you find a match:如果您真的需要找出答案,我想您可以遍历格式直到找到匹配项:

string[] formats = new[] { "dd/MM/yyyy", "dd/MM/yyyy HH:mm:ss" };
string input = "08/01/2020 00:00:00";

string usedFormat = null;
DateTime date;

foreach (string format in formats)
{
    if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
    {
        usedFormat = format;
        break;
    }
}

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

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