2009-08-17 10 views
5

タイトルが述べるように、時間と秒なしでDateTimeと比較する最良の方法は何ですか?時間と秒のない2つのdatetimesを比較します。

私は文字列に私の日付を変換したくない、と

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

ようなソリューションは、かなり気に醜いです。

編集:ああ私の神様、どういうふうに感じますか?もちろん、Dateプロパティを使用することができます。

「別の質問」:DateTimeをYear、Month、Day、Hour、Minuteと比較する最善の方法は何ですか。

ありがとうございました

+0

多分あなたはそれはあなたが測定したいものは何でもサイズに収まるまで、適切にスケールダウン、.Ticksの周りマックすることができ、あなたの他の質問に答えるために。しかし、私はおそらくフィールドをチェックする明示的な方法と一緒に行くだろう。 –

答えて

16

これは何ですか?

DateTime.Now.Date 
+0

絶対に、私はその財産を知っていた。どのように愚かな私は感じる。 – alexn

3

Dateプロパティを見てみましょう、あなたはdt2.Dateでdt1.Dateを比較することができます。

1

DateTimeオブジェクトのDateプロパティを使用できます。例えば

、 日時dateOne

dateOne.Dateプロパティは、日付の部分を使用します。あなたがDateTimeの

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

の拡張子を作成しても、それを使用して美しいですができ、例えば:あなたは、単に使用することができます受け入れ答えよりもDateTime.Now.EqualsIgnoreSeconds(b)

0

回答:

DateTime.Today 
1

でもシンプルな「他人の質問には

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); 
関連する問題