简体   繁体   English

DateTime.TryParse()问题,而将德国日期转换为美国日期

[英]DateTime.TryParse() issue while converting German date to US date

Currently I'm having hard time finding how to resolve my problem related to the DateTime.TryPase function 目前,我很难找到解决与DateTime.TryPase函数有关的问题的方法

        String formattedDateString = String.Empty;

        // German date dd.mm.yyyy
        string dateString = "14.03.2016";
        DateTimeFormatInfo dateTimeFormat = null;

        //automatically throws and exception if the locale is not in the correct format
        CultureInfo fromCulture = new CultureInfo("en-US");
        DateTime tryParseDateTime;


        //automatically throws and exception if the locale is not in the correct format
        CultureInfo toCulture = new CultureInfo("de-de");
        dateTimeFormat = toCulture.DateTimeFormat;

        // expecting result to fail
        if (DateTime.TryParse(dateString, fromCulture, DateTimeStyles.None, out tryParseDateTime))
        {
            formattedDateString = tryParseDateTime.ToString("d", dateTimeFormat);
            Console.WriteLine("success");
        }
        else
        {
            Console.WriteLine("Failed");
        }

So here in my Code, I'm sending German format date ie dd.mm.yyyy and expecting the DateTime.TryParse to fail but since the day is below 12, it assumes that has month and returns the success statement. 因此,在我的代码中,我要发送德语格式的日期,即dd.mm.yyyy,并期望DateTime.TryParse失败,但是由于该日期小于12,因此它假定该月份为月,并返回成功语句。

If I pass the German date "15.03.2016" this works fine. 如果我通过德国日期“ 15.03.2016”,则效果很好。

How can I resolve my problem here. 我如何在这里解决我的问题。

Here the requested locale is German 这里要求的语言环境是德语

Thanks 谢谢

Note: The questioner expects the conversion to fail with the given German format input string. 注意:发问者期望使用给定的德语格式输入字符串,转换会失败。 He only wants the conversion to succeed when the input string is NOT in the German format but in the US format. 他只希望输入字符串不是德语格式而是美国格式时转换成功。


Use DateTime.TryParseExact and pass in the expected format from your source culture. 使用DateTime.TryParseExact并从您的源区域中传入所需的格式。

    // German date dd.mm.yyyy
    string dateString = "01.03.2016";

    CultureInfo fromCulture = new CultureInfo("en-US");
    DateTime tryParseDateTime;

    // expecting result to fail
    if (DateTime.TryParseExact(dateString, fromCulture.DateTimeFormat.ShortDatePattern, fromCulture, DateTimeStyles.None, out tryParseDateTime))
    {
        MessageBox.Show("Success");
    }
    else
    {
        MessageBox.Show("Failed");
    }

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

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