簡體   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