C#获取友好时间差

        /// <summary>
        /// 获取时间差
        /// </summary>
        /// <param name="dtOld">要减的时间</param>
        /// <param name="dtNow">大的时间</param>
        /// <returns></returns>
       public static string  GetDateDiff(DateTime dtOld,DateTime dtNow)
       {
           TimeSpan tsOld = new TimeSpan(dtOld.Ticks);
           TimeSpan tsNow= new TimeSpan(dtNow .Ticks );
           TimeSpan datediff = tsOld.Subtract(tsNow).Duration();
           if (Convert.ToInt32(datediff.Days) <=0)
           {
               if (Convert.ToInt32(datediff.Hours) <= 0)
               {
                   if (Convert.ToInt32(datediff.Minutes) > 0)
                   {
                       return datediff.Minutes.ToString() + "分钟前";
                   }
                   else
                   {
                       return "";
                   }
               }
               else
               {
                   return datediff.Hours .ToString() + "小时前";
               }
           }
           else 
           {
               if (Convert.ToInt32(datediff.Days) < 365)
               {
                   return datediff.Days.ToString() + "天前";
               }
               else
               {
                   int year = Convert.ToInt32(datediff.Days) / 365;
                   return year .ToString ()+ "年前";
               }
           }

       }

 

posted @ 2014-09-16 11:20  Vivu  阅读(367)  评论(0编辑  收藏  举报