使用C#把发表的时间改为几年前,几个月,几天前,几小时前,几分钟前,或几秒前

我们在评论中往往会看到多少天前,多少小时前。 

实现原理:现在时间-过去时间 得到的时间差来做比较

下面我定义了一个Helper类,大家直接引用即可,参数就是时间差,注意时间差类型是TimeSpan类型,而不是DateTime类型哦~

TimeHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 时间测试
{
    /// <summary>
    /// 根据过去和现在的两个DateTime时间差计算出评论大概时间
    /// </summary>
    public class TimeHelper
    {
        public static string GetTimeSpan(TimeSpan ts)
        {
            if (Math.Floor(ts.TotalDays)>365)
            {
                return Math.Floor(ts.TotalDays) / 365 + "年前";
            }
            else if(Math.Floor(ts.TotalDays)>30)
            {
                return Math.Floor(ts.TotalDays) / 30 + "月前";
            }
            else if(Math.Floor(ts.TotalDays)>1)
            {
                return Math.Floor(ts.TotalDays) + "天前";
            }
            else if(Math.Floor(ts.TotalHours)>1)
            {
                return Math.Floor(ts.TotalHours) + "小时前";
            }
            else if(Math.Floor(ts.TotalMinutes)>1)
            {
                return Math.Floor(ts.TotalMinutes) + "分钟前";
            }
            else
            {
                return Math.Floor(ts.TotalSeconds) + "秒前";
            }

        }

    }
}

 

posted @ 2017-01-07 14:44  shuai7boy  阅读(1248)  评论(0编辑  收藏  举报