2011-04-05 68 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... 
} 
相關問題