欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#中返回文章发表的时间差的示例

程序员文章站 2023-12-10 22:43:46
复制代码 代码如下: public static string datediff(datetime datetime1, datetime datetime2)&...
复制代码 代码如下:

 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;
         }