[英]String was not recognized as a valid DateTime
This is my first post here. 这是我在这里的第一篇文章。 The application is a winform I have set the culture for the application as en-GB but while checking and saving I convert it back to en-US I get this the error String was not recornized 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;
}
What am I doing wrong here 我在这里做错了什么
This is my converCurrentCulture code 这是我的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;
This is what I did to get it to work, but if a user selects an invalid date like 29/02/2013 will it work not sure, 这就是我要使其正常工作的方法,但是如果用户选择的日期无效(如2013年2月29日),它将无法正常工作,
CultureInfo currentCulture = new CultureInfo("en-GB");
string date = DateTime.Now.ToString("dd/MM/yyyy", currentCulture);
Since the application is default to en-GB 由于该应用程序默认为en-GB
if (DateTime.Parse(input) > DateTime.Parse(date))
{
return false;
}
else
{
return true;
}
If this is actually your code: 如果这实际上是您的代码:
CultureInfo currentCulture = new CultureInfo("en-US");
string strCheckDate = CheckConvertCulture(input);
if (DateTime.ParseExact(strCheckDate,currentCulture.ToString(),null)
then the problem is in your ParseExact, which translates to 那么问题出在您的ParseExact中,即
if (DateTime.ParseExact(strCheckDate, "en-US", null))
You would be better off specifying the date in a specific format, and parsing that: 您最好以特定的格式指定日期,然后解析该日期:
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))
My big question is - why are you doing this? 我的大问题是-您为什么要这样做? If you have two dates, why are you converting them both to strings, and then converting them back to dates to compare them?
如果您有两个日期,为什么要将它们都转换为字符串,然后再将其转换回日期以进行比较?
return (input > date);
Please see the MSDN documentation for the proper use of DateTime.ParseExact. 请参阅MSDN文档以正确使用DateTime.ParseExact。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.