繁体   English   中英

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

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

目前,我很难找到解决与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");
        }

因此,在我的代码中,我要发送德语格式的日期,即dd.mm.yyyy,并期望DateTime.TryParse失败,但是由于该日期小于12,因此它假定该月份为月,并返回成功语句。

如果我通过德国日期“ 15.03.2016”,则效果很好。

我如何在这里解决我的问题。

这里要求的语言环境是德语

谢谢

注意:发问者期望使用给定的德语格式输入字符串,转换会失败。 他只希望输入字符串不是德语格式而是美国格式时转换成功。


使用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