繁体   English   中英

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

[英]String was not recognized as a valid DateTime

这是我在这里的第一篇文章。 该应用程序是Winform,我已将该应用程序的区域性设置为en-GB,但是在检查并保存后将其转换回en-US,我得到此错误,字符串未重新定义为有效的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;

这就是我要使其正常工作的方法,但是如果用户选择的日期无效(如2013年2月29日),它将无法正常工作,

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;
}

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

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文档以正确使用DateTime.ParseExact。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM