欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

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

时间:2021-12-16 09:50:04|栏目:.NET代码|点击:
复制代码 代码如下:

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

上一篇:ASP.NET Core中间件初始化的实现

栏    目:.NET代码

下一篇:c#事件使用示例详解

本文标题:c#中返回文章发表的时间差的示例

本文地址:http://www.codeinn.net/misctech/187055.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有