获取类似QQ似的时间,昨天或具体日期

     最近在做一个聊天功能,并且要在用户列表上显示最后聊天时间,类似QQ的日期显示。 问群里和百度后,群里没人鸟我,网上也没搜到,最后苦于无奈只能自己封装了。 不过话说回来了,大哥与小弟的区别就是大哥写好封装类让小弟去用。和编译器差不多原理,微软为我们封装了一个又一个类库,然后我们点点就出来了。但这样不能锻炼我们,所以提倡大家多做封装。好了,废话少说,直接上代码,如有不正确的地方欢迎指出!~嘿嘿

   ChateTimeHelper.cs

 /// <summary>
    /// 聊天日期展示帮助类
    /// </summary>
    public  class ChateTimeHelper
    {
        
        /// <summary>
        ///不是本年------则返回具体年-月-日 
        ///是本年,不是今天和昨天------就显示 月-日
        ///昨天----则显示昨天
        ///今天----则显示 时-分
        /// </summary>
        /// <param name="ct">聊天时间</param>
        /// <returns></returns>
        public static  string GetChateTimeInfo(DateTime ct)
        {
            DateTime dtNow = DateTime.Now;                   
            int year=dtNow.Year;
            int month=dtNow.Month;
            int day=dtNow.Day;
            TimeSpan ts = dtNow - ct;                     
            if (ct.AddDays(1).Year == year && ct.AddDays(1).Month == month && ct.AddDays(1).Day == day)//加一天如果和现在年月日相同,证明是昨天
            {
                return "昨天";
            }
            else if (ct.Year==year&&ct.Month==month&&ct.Day==day)//年月日相等则证明是今天发的消息
            {
                string hour = ct.Hour < 10 ? "0" + ct.Hour.ToString() : ct.Hour.ToString();
                string minute = ct.Minute < 10 ? "0" + ct.Minute.ToString() : ct.Minute.ToString();
                return hour + ":" + minute;             
            }
            else if (ct.Year == year)
            {
                return ct.Month + "-" + ct.Day;
            }
            else //其余的显示月日
            {
                return ct.Year + "-" + ct.Month + "-" + ct.Day;
            }
        }
    }

 调用上面的类就会获得类似下面的这种结果:

原文地址:https://www.cnblogs.com/shuai7boy/p/6405294.html