• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

通过扩展方法,将C#的DateTime(日期)转换成人性化的显示

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

不需要什么说明,直接帖代码:

        /// <summary>
        /// 将日期转换成人性化的显示
        /// </summary>
        /// <param name="date">当前时间</param>
        /// <returns></returns>
        public static string ToPrettyDate(this DateTime date)
        {
            var timeSince = DateTime.Now.Subtract(date);
            if (timeSince.TotalMilliseconds < 1) return "还未到";
            if (timeSince.TotalMinutes < 1) return "刚刚";
            if (timeSince.TotalMinutes < 2) return "1 分钟前";
            if (timeSince.TotalMinutes < 60) return string.Format("{0} 分钟前", timeSince.Minutes);
            if (timeSince.TotalMinutes < 120) return "1 小时前";
            if (timeSince.TotalHours < 24) return string.Format("{0} 小时前", timeSince.Hours);
            if (timeSince.TotalDays == 1) return "昨天";
            if (timeSince.TotalDays < 7) return string.Format("{0} 天前", timeSince.Days);
            if (timeSince.TotalDays < 14) return "上周";
            if (timeSince.TotalDays < 21) return "2 周前";
            if (timeSince.TotalDays < 28) return "3 周前";
            if (timeSince.TotalDays < 60) return "上个月前";
            if (timeSince.TotalDays < 365) return string.Format("{0} 个月前", Math.Round(timeSince.TotalDays / 30));
            if (timeSince.TotalDays < 730) return "去年";
            return string.Format("{0} 年前", Math.Round(timeSince.TotalDays / 365));
        }

或者

const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;

if (delta < 0)
{
  return "not yet";
}
if (delta < 1 * MINUTE)
{
  return ts.Seconds == 1 ? "1秒前" : ts.Seconds + "秒前";
}
if (delta < 2 * MINUTE)
{
  return "1分钟之前";
}
if (delta < 45 * MINUTE)
{
  return ts.Minutes + "分钟";
}
if (delta < 90 * MINUTE)
{
  return "1小时前";
}
if (delta < 24 * HOUR)
{
  return ts.Hours + "小时前";
}
if (delta < 48 * HOUR)
{
  return "昨天";
}
if (delta < 30 * DAY)
{
  return ts.Days + " 天之前";
}
if (delta < 12 * MONTH)
{
  int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
  return months <= 1 ? "一个月之前" : months + "月之前";
}
else
{
  int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
  return years <= 1 ? "一年前" : years + "年前";
}

 

谢谢浏览!


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
企业信息化系统基础——AD:使用C#批量创建帐号发布时间:2022-07-10
下一篇:
C#利用反射,遍历获得一个类的所有属性名发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap