簡體   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