2013-03-15 71 views
0

这是我第一篇文章。该应用程序是我已经设置了培养应用为EN-GB一个winform但同时检查并保存我将其转换回为en-US我得到这个错误字符串未被recornized为有效的DateTime字符串未被识别为有效日期时间

CultureInfo currentCulture = new CultureInfo("en-US"); 
string strCheckDate = CheckConvertCulture(input); 
string date = DateTime.Now.ToString("M/d/yyyy"); 

if (DateTime.ParseExact(strCheckDate,currentCulture.ToString(),null)> DateTime.ParseExact(date,currentCulture.ToString(),null)) 
{ 
     return false; 
} 
else 
{ 
     return true; 
} 

我在做什么错在这里

这是我converCurrentCulture代码

string strdate = string.Empty; 
CultureInfo currentCulture = CultureInfo.CurrentCulture; 
System.Globalization.DateTimeFormatInfo usDtfi = new System.Globalization.CultureInfo("en-US", false).DateTimeFormat; 
if (currentCulture.ToString() != "en-US") 
{ 
    strdate = Convert.ToDateTime(Culturedate).ToString(usDtfi.ShortDatePattern); 
} 
else 
{ 
    strdate = Culturedate; 
} 

    return strdate; 

这是我做过什么来得到它的工作,但如果用户选择像29/02/2013无效的日期将它的工作不确定,

CultureInfo currentCulture = new CultureInfo("en-GB"); 
string date = DateTime.Now.ToString("dd/MM/yyyy", currentCulture); 

由于应用程序默认为EN-GB

if (DateTime.Parse(input) > DateTime.Parse(date)) 
{ 
    return false; 
} 
else 
{ 
    return true; 
} 
+1

没有提供'CheckConvertCulture'的定义,你不会得到一个好的答案。 – spender 2013-03-15 11:33:56

+0

什么是'strCheckDate'和'CheckConvertCulture'? – 2013-03-15 11:35:03

+0

strCheckDate只是从下拉日期,需要找出如何编辑我的代码,并把CheckConvertCulture :) – Adrian 2013-03-15 11:39:03

回答

0

如果这实际上是你的代码:

CultureInfo currentCulture = new CultureInfo("en-US"); 
string strCheckDate = CheckConvertCulture(input); 

if (DateTime.ParseExact(strCheckDate,currentCulture.ToString(),null) 

那么问题是在你的ParseExact,转化为

if (DateTime.ParseExact(strCheckDate, "en-US", null)) 

你会被打赌然后解析:

string format = "MM/dd/yyyy HH:mm:ss"; 
string strCheckDate = input.ToString(format); 

// See note below about "why are you doing this?  
if (DateTime.ParseExact(strCheckDate, format)) 

我的一个大问题是 - 为什么你要这样做?如果你有两个日期,你为什么要将它们都转换为字符串,然后将它们转换回日期进行比较?

return (input > date); 

请参阅MSDN documentation以正确使用DateTime.ParseExact。

+0

我有一个组合框,用户选择日期以便以字符串格式然后我得到当前的日期,并将其转换为当前的文化,这是en-GB,但我保存在en-US – Adrian 2013-03-15 12:14:57

+0

没问题,但没有任何理由将当前日期转换为字符串然后回到日期。不要让事情比他们需要的更复杂。 – 2013-03-15 12:53:15

+0

如果我不转换它,如何检查日期格式的字符串? – Adrian 2013-03-15 12:55:12

相关问题