【问题标题】:String was not recognized as a valid DateTime error when compare two datetime variable比较两个日期时间变量时,字符串未被识别为有效的日期时间错误
【发布时间】:2017-06-06 09:34:45
【问题描述】:
string date1="06/06/2017";
string date2="06/05/2017";

日期格式为mm/dd/yyyy。我需要比较两个日期

string test = DateTime.ParseExact(date1, "DD/M/yyyy", CultureInfo.InvariantCulture);

我无法找出为什么会出现错误,例如 String 未被识别为有效的 DateTime

【问题讨论】:

  • 如果您的日期在“mm/dd/yyyy”中,为什么要解析为“DD/M/yyyy”?
  • 像这样:var test = DateTime.ParseExact(date1, "dd/MM/yyyy", CultureInfo.InvariantCulture);
  • 老实说,你在谷歌上搜索过错误信息吗(String was not recognized as a valid DateTime

标签: c# .net datetime


【解决方案1】:

日期格式为"mm/dd/yyyy"

如果日期采用这种格式,请在 ParseExact() 中使用 "MM/dd/yyyy"

var test = DateTime.ParseExact(date1, "MM/dd/yyyy", CultureInfo.InvariantCulture);

另外,ParseExact() 返回 DateTime,而不是 string。使用varDateTime

【讨论】:

  • 需要注意的是它只适用于InvariantCulture,否则使用本地日期分隔符。
  • else if (DateTime.ParseExact(date1, "MM/dd/yyyy", CultureInfo.InvariantCulture).Date
  • @priyathapliyal,解析date2 时使用"dd/MM/yyyy"。使用"MM/dd/yyyy"
  • 字符串未被识别为有效的日期时间
  • @priyathapliyal,你使用的日期和问题一样吗?
【解决方案2】:

像这样使用 ToString() 方法 DateTime.ParseExact(date1,"MM/dd/yyyy",CultureInfo.InvariantCulture).ToString(); 这应该可以解决您的问题。问题是您不能将 DateTime 隐式转换为字符串。

【讨论】:

  • @priyathapliyal 您必须将 DateTime 对象转换为字符串。 DateTime.ParseExact 返回 DateTime 因此您必须使用 ToString() 将其转换为字符串
猜你喜欢
  • 1970-01-01
  • 2013-02-07
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多