DateTime.TryParse()发行日期德国转换为美国日期

问题描述:

目前我有很难找到如何解决我的问题涉及到DateTime.TryPase功能DateTime.TryParse()发行日期德国转换为美国日期

 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”这工作正常。

我该如何解决我的问题。

这里所要求的语言环境为德

感谢

+2

悉心为你传递美国文化从转换一开始,我以为这应该是'去DE'? – DavidG

+0

由于OP的错误,投票结束。 – t0mm13b

+1

尝试[DateTime.ParseExact](https://msdn.microsoft.com/en-us/library/w2sa9yss(v = vs.110).aspx) –

注:提问者预计转换失败与给定的格式德国输入字符串。他只希望在输入字符串不是德文格式而是美式格式时转换成功。


使用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"); 
    } 
+0

这工作正常,当我们通过日期时间模式时结果失败 –