字符串未被识别为有效的DateTime

时间:2013-03-15 11:31:52

标签: c# datetime

这是我在这里的第一篇文章。该应用程序是一个winform我已经为应用程序设置了en-GB的文化,但在检查和保存时我将其转换回en-US我得到这个错误String没有被重新定义为有效的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 个答案:

答案 0 :(得分: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。