c#中字符串日期的比较和平等

时间:2014-01-04 02:31:43

标签: c#

我有两个字符串日期,我想检查两个字符串日期是否相等。第一个日期是yyyy-mm-dd格式,第二个日期是yyyy-mm-dd HH:MM:SS格式。

如何在C#中比较和检查两个日期的相等性?

编辑:是否可以确定日期的格式?因为有时无法识别哪个日期是哪种格式。日期来自差异数据库。

1 个答案:

答案 0 :(得分:1)

一种简单的方法是:

shortDate == longDate.Substring(0,10)

更好的方法是解析它们:

DateTime
  .ParseExact(shortDate, "yyyy-MM-dd", CultureInfo.InvariantCulture) == 
DateTime
  .ParseExact(longDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)
  .Date

编辑:

var DateFormats = new string[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" };

DateTime
  .ParseExact(shortDate, DateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None)
  .Date == 
DateTime
  .ParseExact(longDate, DateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None)
  .Date