2016-10-15 4 views
2

私は以下のコードを持っています。それはほとんどのシナリオでは機能しますが、今日私はexpiration_date09/30/2017 00:00:00である1つのシナリオがstring10/15/2016 14:34:19にあるcurrentDateTimeよりも小さいですか?私はちょうどstringと比較して私の側のバグは何ですか?C#2日時を比較する正しい方法

System.DateTime expiration_date = newVer.License.Status.Expiration_Date; 
    DateTime currentDateTime = DateTime.Now; 
    currentDateTime.ToString("MM/dd/yyyy HH:mm:ss"); 
    int a = expiration_date.ToString("MM/dd/yyyy HH:mm:ss") 
      .CompareTo(currentDateTime.ToString("MM/dd/yyyy HH:mm:ss")); 
    //MessageBox.Show("int a is :" + a); 
    if (expiration_date.ToString("MM/dd/yyyy HH:mm:ss") 
      .CompareTo(currentDateTime.ToString("MM/dd/yyyy HH:mm:ss")) < 1) 
    { 
     crossDate = 1;    
     MessageBox.Show("Cross Date Alert"+ " Expiry Date Is :"+ 
         expiration_date.ToString("MM/dd/yyyy HH:mm:ss") 
         + " "+"Current Date Is :"+ 
         currentDateTime.ToString("MM/dd/yyyy HH:mm:ss")); 
    } 
+0

日付を文字列に変換するのではなく、直接比較する必要があります。比較前に文字列に変換することを依頼している場合は、増加する日付、つまりyyyy/MM/dd HH:mm:ss "' –

+0

の形式を使用する必要があります。変換するには 'insist'する必要はありません2つの日付を比較する文字列に2つの日付。実際には変換のために「遅い」です。あなたが他のことができない限り、値のドメインを変更しないでください。 – shadow

答えて

5

は、日時の比較文字列に変換しません

DateTime expiration_date = newVer.License.Status.Expiration_Date.Date; 
    DateTime currentDateTime = DateTime.Now.Date; 

2日の日差を使用することもできます。

int daydiff = (int)((currentDateTime - expiration_date).TotalDays) 
+0

どちらが良いでしょうか? – user5313398

+0

@ user5313398あなたは時間が必要な場合を除き、日付の使用だけが良いと思います。 –

+0

@ user5313398 2日の日差を使用することもできます。 –

1

は、日付の例を比較します

  DateTime d1 = DateTime.Now; 
      DateTime d2 = DateTime.Now.AddDays(1); 

      if (d2.CompareTo(d1)>0) 
       Console.WriteLine("d2>d1"); 
      else 
       Console.WriteLine("d2<=d1"); 
+0

それは割り当てられる必要はありませんか? – user5313398

+0

'Dates'を' Strings'と比較する必要があります。 – shadow

1

あなたの質問は2部構成の答えを持っています。もっと簡単なことがありますが、

まず、文字列をDateTimeオブジェクトに変換します。 DateTimeクラスには、これを支援するいくつかのメソッドがあります。 ParseExactを試してみてください。

次に、DateTimeオブジェクトをUnixタイムスタンプに変換します。

ここでは、2つのlong intがあり、これを比較してint比較を別のDateTimeに変換し、そこから物事を取ります。

1

は、あなたが使用して日付だけではなく、時間が必要な場合は、

DateTime expiration_date = newVer.License.Status.Expiration_Date; 
DateTime currentDateTime = DateTime.Now; 
if(expiration_date < currentDateTime) 
{ 
    // expired 
} 

ような数字を比較すると同じように

 DateTime expiration_date = newVer.License.Status.Expiration_Date; 

     if (expiration_date.CompareTo(DateTime.Now) < 1) 
     { 
      MessageBox.Show("Cross Date Alert"+ " Expiry Date Is :"+ expiration_date.ToString("MM/dd/yyyy HH:mm:ss") + " "+"Current Date Is :"+ currentDateTime.ToString("MM/dd/yyyy HH:mm:ss")); 
     } 
+0

@ user5313398、それを通過しましたか? – user3598756