C#实现两个日期比较大小

  DateTime t1 = new DateTime(100);

  DateTime t2 = new DateTime(20);

  if (DateTime.Compare(t1, t2) > 0) Console.WriteLine("t1 > t2");

  if (DateTime.Compare(t1, t2) == 0) Console.WriteLine("t1 == t2");

  if (DateTime.Compare(t1, t2) < 0) Console.WriteLine("t1 < t2");

  //1。比较时间大小的实验

  string st1="12:13";

  string st2="14:14";

  DateTime dt1=Convert.ToDateTime(st1);

  DateTime dt2=Convert.ToDateTime(st2);

  DateTime dt3=DateTime.Now;

  if(DateTime.Compare(dt1,dt2)>0)

  msg.Text=st1+">"+st2;

  else

  msg.Text=st1+"<"+st2;

  msg.Text+="

  "+dt1.ToString();

  if(DateTime.Compare(dt1,dt3)>0)

  msg.Text+="

  "+st1+">"+dt3.ToString();

  else

  msg.Text+="

  "+st1+"<"+dt3.ToString();

  //2。计算两个时间差值的函数,返回时间差的绝对值:

  private string DateDiff(DateTime DateTime1,DateTime DateTime2)

  {

  string dateDiff=null;

  try

  {

  TimeSpan ts1=new TimeSpan(DateTime1.Ticks);

  TimeSpan ts2=new TimeSpan(DateTime2.Ticks);

  TimeSpan ts=ts1.Subtract(ts2).Duration();

  dateDiff=ts.Days.ToString()+"天"

  +ts.Hours.ToString()+"小时"

  +ts.Minutes.ToString()+"分钟"

  +ts.Seconds.ToString()+"秒";

  }

  catch

  {

  }

  return dateDiff;

  }

  //3。实现计算DateTime1-36天=DateTime2的功能

  TimeSpan ts=new TimeSpan(40,0,0,0);

  DateTime dt2=DateTime.Now.Subtract(ts);

  msg.Text=DateTime.Now.ToString()+"-"+ts.Days.ToString()+"天

  ";

  msg.Text+=dt2.ToString();

  use "DateTime.Compare" static method

  DateTime.Compare( dt1, dt2 ) > 0 : dt1 > dt2

  DateTime.Compare( dt1, dt2 ) == 0 : dt1 == dt2

  DateTime.Compare( dt1, dt2 ) < 0 : dt1 < dt2

  ///

  /// 计算两个日期的时间间隔

  ///

  /// 第一个日期和时间

  /// 第二个日期和时间

  ///

  private string DateDiff(DateTime DateTime1, DateTime DateTime2)

  {

  string dateDiff = null;

  TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);

  TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);

  TimeSpan ts = ts1.Subtract(ts2).Duration();

  dateDiff = ts.Days.ToString()+"天"

  + ts.Hours.ToString()+"小时"

  + ts.Minutes.ToString()+"分钟"

  + ts.Seconds.ToString()+"秒";

  return dateDiff;

  }