简体   繁体   English

C# 使用 DateTime.TryParseExact() 多种格式解析 DateTime

[英]C# Parse DateTime using DateTime.TryParseExact() multiple format

I have a string text that i want to parse/convert to DateTime,我有一个string text ,我想解析/转换为 DateTime,
the text can have a different formats (depending on the user who write it),文本可以有不同的格式(取决于编写它的用户),
it can be "dd/MM/yyyy" or it can be "MM/dd/yyyy".它可以是“dd/MM/yyyy”或“MM/dd/yyyy”。

I am using DateTime.TryParseExact(string, formats[], provider, dateTimeStyles, out result)我正在使用DateTime.TryParseExact(string, formats[], provider, dateTimeStyles, out result)
as descripted here TryParseExact如此处所述TryParseExact

Now the problem happens in the following cases现在问题发生在以下情况
if (for example) string text = "06/01/2023"如果(例如) string text = "06/01/2023"

The text could have two meanings text可能有两种含义
1 st --> Day: 06 , Month: 01 , Year: 2023 1 st --> 日: 06 ,月: 01 ,年:2023
2 nd --> Day: 01 , Month: 06 , Year: 2023 2 nd --> 日: 01 ,月: 06 ,年:2023

My Question is when does the Method TryParseExact() return true我的问题是方法TryParseExact()何时返回true
does it return true for the first format that matches text ?它是否为第一个匹配textformat返回 true ?
or does it evalute all/each format inside the formats[] array?或者它是否评估formats[]数组中的所有/每种格式?

i have tried to search for a similar question, but i didn't seem to find one,我试图搜索类似的问题,但我似乎没有找到,
i have tried read this reference TryParseExactMultiple我试过阅读这个参考TryParseExactMultiple
i have tried this question我试过这个问题

Thank you for your help in advance.提前谢谢你的帮助。

My code:我的代码:

string text = "06/01/2023";

string[] formatsArray = new string[]
{
  "yyyyMMdd",
  "dd/MM/yyyy",
  "dd-MMM-yy",
  "MM/dd/yyyy",
  "MM-dd-yyyy"
};

DateTime result;

DateTime.TryParseExact(text, formatsArray, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out result)

Output is:输出是:
result = Day: 06, Month: 01, Year: 2023

It seems that source code is pretty clear - TryParseExact calls TryParseExactMultiple which cycles formats in provided order and returns first one that succeeds: 源代码似乎很清楚TryParseExact调用TryParseExactMultiple ,它按提供的顺序循环格式并返回第一个成功的格式:

internal static bool TryParseExactMultiple(ReadOnlySpan<char> s, string?[]? formats,
    DateTimeFormatInfo dtfi, DateTimeStyles style, scoped ref DateTimeResult result)
{
    // ...

    // Do a loop through the provided formats and see if we can parse successfully in
    // one of the formats.
    for (int i = 0; i < formats.Length; i++)
    {
        string? format = formats[i];
        // ...
        if (TryParseExact(s, format, dtfi, style, ref innerResult))
        {
            result.parsedDate = innerResult.parsedDate;
            result.timeZoneOffset = innerResult.timeZoneOffset;
            return true;
        }
    }

    result.SetBadDateTimeFailure();
    return false;
}

Since documentation does not specify behaviour for I would not recommend to rely on it, if it is possible, or possibly wrap this into helper method which will be tested for your particular requirements.由于文档没有指定行为,因此我不建议依赖它,如果可能的话,或者可能将其包装到将根据您的特定要求进行测试的辅助方法中。

In general - when accepting data from somewhere you need to agree on data format, if the source of the data is not under your control - contact the vendor to clarify it otherwise sooner or later the situation like this are bound to happen (in theory not only related to dates).一般来说 - 当从某个地方接受数据时你需要就数据格式达成一致,如果数据的来源不受你的控制 - 联系供应商澄清它否则迟早会发生这样的情况(理论上不会仅与日期有关)。

According to the documentation , TryParseExact does not provide an indication for which format was used.根据文档,TryParseExact 不提供使用哪种格式的指示。 My general recommendation is to allow users to send only one date format.我的一般建议是允许用户只发送一种日期格式。

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

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