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

c#友好显示日期 c#日期datetime使用方法

程序员文章站 2024-02-25 21:58:09
复制代码 代码如下:#region 友好显示时间        /// ...

复制代码 代码如下:

#region 友好显示时间
        /// <summary>
        /// 友好显示时间
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string showtime(datetime date)
        {
            const int second = 1;
            const int minute = 60 * second;
            const int hour = 60 * minute;
            const int day = 24 * hour;
            const int month = 30 * day;
            timespan ts = datetime.now - date;
            double delta = ts.totalseconds;
            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 + "年前";
            }
        }
        #endregion