2009-08-17 53 views
5

正如標題所述,與沒有小時和秒鐘的DateTime進行比較的最佳方法是什麼?比較兩個日期時間 - 無小時和秒

我不想我的日期轉換爲字符串,像

DateTime.Now.Year == last.Year && DateTime.Now.Month == last.Month && DateTime.Now.Day == last.Day

的解決方案真的是太醜陋。

編輯:哦,我的上帝,我覺得多麼愚蠢。當然你可以使用Date屬性。

「另一個問題」:將DateTime與Year,Month,Day,Hour,Minute進行比較,但不是秒的最佳方法是什麼?

謝謝

+0

爲了回答您的其他問題,也許你可以弄髒周圍.Ticks,適當縮放它,直到它符合您要衡量任何尺寸。但我可能只是用明確的方法來檢查字段。 – 2009-08-17 07:37:59

回答

16

是這樣的:你在找什麼?

DateTime.Now.Date 
+0

絕對,該死的我知道那個財產。我感覺多麼愚蠢。 – alexn 2009-08-17 07:31:33

3

看看Date屬性,然後你可以比較dt1.Date和dt2.Date。

1

您可以使用DateTime對象的Date屬性。

例如, 日期時間dateOne

dateOne.Date屬性將僅使用日期部分。

0

答案爲「其他」的問題:你可以爲日期時間

創建擴展
public static bool EqualsIgnoreSeconds(this DateTime a, DateTime b) 
{ 
    // the ugly code 
} 

但是如果使用它是美麗的,如:DateTime.Now.EqualsIgnoreSeconds(b)

1

即使比你可以簡單地使用接受的答案更簡單:

DateTime.Today 
1

關於不秒的比較,只要使用此:

public static bool EqualsIgnoringSeconds(this DateTime source, DateTime target) 
{ 
    return TimeSpan.FromTicks(source.Ticks).TotalMinutes == TimeSpan.FromTicks(target.Ticks).TotalMinutes; 
} 
0
using System; 

namespace Rextester 
{ 
    public class Program 
    { 
     public static void Main(string[] args) 
     { 
      DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0); 
      DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0); 
      int result = DateTime.Compare(date1.Date, date2.Date); 
      string relationship; 

      if (result < 0) 
      relationship = "is earlier than"; 
      else if (result == 0) 
      relationship = "is the same time as";   
      else 
      relationship = "is later than"; 

      Console.WriteLine("{0} {1} {2}", date1, relationship, date2); 
     } 
    } 
} 

此行是至關重要的:

int result = DateTime.Compare(date1.Date, date2.Date);