程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> c#中返回文章發表的時間差的示例

c#中返回文章發表的時間差的示例

編輯:C#基礎知識
代碼如下:

 public static string DateDiff(DateTime DateTime1, DateTime DateTime2)
         {
             string dateDiff = null;
             int date = 0;
             try
             {
                 int year = Convert.ToInt32(DateTime2.ToString("yyyy")) - Convert.ToInt32(DateTime1.ToString("yyyy"));
                 TimeSpan ts = DateTime2 - DateTime1;
                 string t1 = DateTime1.ToString("yyyy-MM-dd");
                 string t2 = DateTime2.ToString("yyyy-MM-dd");
                 DateTime d1 = DateTime.Parse(t1);
                 DateTime d2 = DateTime.Parse(t2);
                 TimeSpan ts2 = d2 - d1;
                 date = ts2.Days;
                 if (date == 0)
                 {
                     if (ts.Hours > 1)
                     {
                         dateDiff = ts.Hours.ToString() + "小時前";
                     }
                     else
                     {
                         if (ts.Minutes > 1)
                         {
                             dateDiff = ts.Minutes.ToString() + "分鐘前";
                         }
                         else
                         {
                             dateDiff = ts.Seconds.ToString() + "秒前";
                         }
                     }
                 }
                 else
                 {
                     if (date == 1)
                     {
                         dateDiff = "昨天";
                     }
                     else
                     {
                         if (date == 2)
                         {
                             dateDiff = "前天";
                         }
                         else
                         {
                             if (year == 0)
                             {
                                 dateDiff = DateTime1.Month.ToString() + "月" + DateTime1.Day.ToString() + "日";
                             }
                             else
                             {
                                 dateDiff = DateTime1.Year.ToString() + "年" + DateTime1.Month.ToString() + "月" + DateTime1.Day.ToString() + "日";
                             }
                         }
                     }
                 }
             }
             catch
             { }
             return dateDiff;
         }          
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved