C# 字符串未被识别为有效的日期时间
这是我在这里的第一篇文章。应用程序是winform,我已将应用程序的区域性设置为en GB,但在检查和保存时,我将其转换回en US,我发现错误字符串未被重新命名为有效的日期时间C# 字符串未被识别为有效的日期时间,c#,datetime,C#,Datetime,这是我在这里的第一篇文章。应用程序是winform,我已将应用程序的区域性设置为en GB,但在检查和保存时,我将其转换回en US,我发现错误字符串未被重新命名为有效的日期时间 CultureInfo currentCulture = new CultureInfo("en-US"); string strCheckDate = CheckConvertCulture(input); string date = DateTime.Now.ToString("M/d/yyyy"); if (D
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;
}
我做错了什么
这是我的对流文化代码
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);
有关DateTime.ParseExact的正确用法,请参阅。如果不提供
CheckConvertCulture
的定义,您将不会得到一个好的答案。什么是strCheckDate
和CheckConvertCulture
?strCheckDate只是下拉列表中的日期,需要了解如何编辑我的代码并放入CheckConvertCulture:)@SonerGönül我添加了CheckConverCulture@TimSchmelter我尝试添加这个字符串date=DateTime.Now.ToString(“M/d/yyyy”,currentCulture);但是我仍然得到了这个错误我有一个组合框,用户选择了字符串格式的日期,然后我得到了当前日期,并在将其转换为当前区域性(en GB)后与用户日期进行了检查,但我保存为en Ust这没问题,但是没有理由将当前日期转换为字符串,然后再返回到日期。不要让事情变得比需要的更复杂。如果我不转换字符串,我如何对照日期格式检查它?您需要将组合框中的值转换为日期(if的左侧),但不必转换当前日期(右侧)。谢谢尝试。但不会是日期时间。现在也给你日期和时间。如果是这样,转换后的字符串是否能够检查是否更大?