2011-04-05 70 views
1

我不知道为什么我的脑袋正在旋转 - 确定是漫长的一天 - 但我需要一些帮助。比较可能不是日期的日期和字符串的最佳方法是什么?

我有一个DateTime变量和一个字符串变量。我最终需要比较两者的平等。 DateTime将为null或DateTime。该字符串可以是以字符串(mm/dd/yy)表示的日期或单个单词。一个简单的布尔表明这两个变量是相等的,只是我需要的,但我真的很困难。

此刻,我得到一个错误,说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; 
} 

仅供参考 - 日期1和date2在顶部只dev的目的初始化。实际值从数据库中提取。


编辑#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; 
    } 
+2

为什么你忽略'DateTime.TryParse'的返回值?你怎么知道它是否成功? – 2011-04-05 21:04:24

+0

你有'date2'声明为可空类型的任何原因? – 2011-04-05 21:04:26

+0

date2在db中被定义为可为空的类型,实际上可能会返回为null。我已经在db中检查过了。 – DenaliHardtail 2011-04-05 21:05:42

回答

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... 
} 
相关问题