C#比較兩時間大小

來源:互聯網
上載者:User

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+="\r\n"+dt1.ToString();
   if(DateTime.Compare(dt1,dt3)>0)
    msg.Text+="\r\n"+st1+">"+dt3.ToString();
   else
    msg.Text+="\r\n"+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()+"天\r\n";
   msg.Text+=dt2.ToString();


該文章轉載自網路大本營:http://www.xrss.cn/Info/8182.Html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.