比较可能不是日期的日期和字符串的最佳方法是什么?

时间:2011-04-05 21:01:23

标签: c# .net-4.0

我不知道为什么我的脑袋正在旋转 - 肯定是漫长的一天 - 但我需要一些帮助。

我有一个DateTime变量和一个String变量。我最终需要比较两者的平等性。 DateTime将为null或DateTime。该字符串将是表示为字符串的日期(mm / dd / yy)或单个单词。一个简单的bool表明两个变量是相同的,这就是我所需要的,但我真的很挣扎。

目前,我收到一条错误消息,指出date2未初始化。建议非常感谢。谢谢!

这是我开始的......

string date1= "12/31/2010";
DateTime? date2= new DateTime(1990, 6, 1);

bool datesMatch = false;

DateTime outDate1;
DateTime.TryParse(date1, out outDate1);

DateTime outDate2;

if (date2.HasValue)
{
   DateTime.TryParse(date2.Value.ToShortDateString(), out outDate2);
}

if (outDate1== outDate2)
{
   datesMatch = true;
}

if (!datesMatch)
{
   // do stuff here;
}

FYI - date1和date2初始化在顶部,仅用于开发目的。实际值从数据库中提取。


编辑#1 - 这是我的最新消息。如何摆脱outDate2未初始化导致的错误?我在那里放置了一个任意日期,它清除了错误。这只是感觉不对。

    string date1 = "12/31/2010";
    DateTime? date2 = new DateTime(1990, 6, 1);

    bool datesMatch = false;

    DateTime outDate1;
    bool successDate1 = DateTime.TryParse(date1, out outDate1);

    DateTime outDate2;
    bool successDate2 = false;

    if (date2.HasValue)
    {
        successDate2 = DateTime.TryParse(date2.Value.ToShortDateString(), out outDate2);
    }

    if (successDate1 && successDate2)
    {
        if (outDate1 == outDate2)
        {
            datesMatch = true;
        }
    }

    if (!datesMatch)
    {
        // do stuff here;
    }

1 个答案:

答案 0 :(得分:6)

DateTime.TryParse返回一个布尔值,因此您知道它是否成功。使用该返回值。

string date1= "12/31/2010";
DateTime? date2= new DateTime(1990, 6, 1);

bool datesMatch = false;

DateTime outDate1;
bool success = DateTime.TryParse(date1, out outDate1);

DateTime outDate2;

if (success)
{
   // etc...
}