如何正确执行 DateTime.Parse

Sta*_*dup 1 c# datetime tryparse

我有以下方法:

    private DateTime GetDateTimeFromString(string dateTimeStr)
    {
        try
        {
            return DateTime.Parse(dateTimeStr, CultureInfo.InvariantCulture);
        }
        catch (Exception ex)
        {
            _logger.Log($"Exception while parsing {dateTimeStr}: {ex.Message}.");

            return DateTime.Now;
        }
    }
Run Code Online (Sandbox Code Playgroud)

当我在 Visual Studio 中运行它时,它工作正常。但是当它部署到 Azure 时它失败了。错误是:

解析 21/4/2019 11:6:56 时出现异常:String 未被识别为有效的 DateTime。

我在调试器中粘贴21/4/2019 11:6:56,它有效。醉了。有人可以帮忙吗?

请注意,无论是否使用 CultureInfo,它都会在 Azure(作为 Web 应用程序)上失败。

同样在 Azure 上,我的 web.config 设置为:

<globalization culture="" uiCulture="" />
Run Code Online (Sandbox Code Playgroud)

D-S*_*hih 5

您可以尝试使用DateTime.TryParseExact并设置解析格式。

DateTime dt;

DateTime.TryParseExact("21/4/2019 11:6:56",
                       "dd/M/yyyy hh:m:ss",
                        System.Globalization.CultureInfo.InvariantCulture,
                        System.Globalization.DateTimeStyles.None,
                        out dt);
Run Code Online (Sandbox Code Playgroud)

我会使用DateTime.TryParseExact而不是有两个原因DateTime.Parse

  1. DateTime.TryParseExactreturn bool,你可以处理它而不是 handle Exception。如果输入字符串与格式和文化不匹配。它会回来false
  2. 确定Culture和日期时间格式为参数。

像这样。

DateTime dt;

if(!DateTime.TryParseExact(dateTimeStr,
                       "dd/M/yyyy hh:m:ss",
                        System.Globalization.CultureInfo.InvariantCulture,
                        System.Globalization.DateTimeStyles.None,
                        out dt))
{
    _logger.Log($"Exception while parsing {dateTimeStr}");
    dt = DateTime.Now;
}

return dt;
Run Code Online (Sandbox Code Playgroud)

c#在线