2つの日付を比較する

DateTimeクラスで表現された2つの日付を比較するには
同クラスの CompareTo 関数を使うか
比較演算子を利用します。(こちらがわかりやすいです。)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 現在時刻
            DateTime now = DateTime.Now;

            // 任意の時刻
            DateTime time1 = new DateTime(2000, 1, 1, 0, 0, 0);

            // 2つを表示
            Console.WriteLine("now = " + now.ToString());
            Console.WriteLine("time1 = " + time1.ToString());

            // 関数で比較
            switch(time1.CompareTo(now))
            {
                case -1:
                    Console.WriteLine("time1 は now より古い");
                    break;
                case 0:
                    Console.WriteLine("time1 と now は等しい");
                    break;
                case 1:
                    Console.WriteLine("time1 は now より新しい");
                    break;
            }

            // 比較演算子で比較(こちらがわかりやすい)
            if(time1 < now)
                Console.WriteLine("time1 は now より古い");
            if(time1 == now)
                Console.WriteLine("time1 と now は等しい");
            if(time1 > now)
                Console.WriteLine("time1 は now より新しい");
        }
    }
}

【結果】

now = 2010/07/05 22:51:14
time1 = 2000/01/01 0:00:00
time1 は now より古い
time1 は now より古い

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)