C#中如何计算相对时间

时间保存在'DateTime'值中,如何显示为相对时间,比如显示:

  • 2小时前
  • 3天前
  • 一个月前

解决方案

这是我的方法

var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
if (delta < 60)
{
  return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
}
if (delta < 120)
{
  return "1分钟前";
}
if (delta < 2700) //45 * 60
{
  return ts.Minutes + " 分钟前";
}
if (delta < 5400) //90 * 60
{
  return "1小时前";
}
if (delta < 86400) //24 * 60 * 60
{
  return ts.Hours + " 小时前";
}
if (delta < 172800) //48 * 60 * 60
{
  return "昨天";
}
if (delta < 2592000) //30 * 24 * 60 * 60
{
  return ts.Days + " 天前";
}
if (delta < 31104000) //12 * 30 * 24 * 60 * 60
{
  int months = Convert.ToInt32(Math.Floor((double)ts.Days/30));
  return months <= 1 ? "一个月之前" : months + " 月前";
}
int years = Convert.ToInt32(Math.Floor((double)ts.Days/365));
return years <= 1 ? "1年前" : years + " 年前";

或者

public static string ToLongString(this TimeSpan time)
{
    string output = String.Empty;
    if (time.Days > 0)
        output += time.Days + " 天 ";
    if ((time.Days == 0 || time.Days == 1) && time.Hours > 0)
        output += time.Hours + " 小时 ";
    if (time.Days == 0 && time.Minutes > 0)
        output += time.Minutes + " 分 ";
    if (output.Length == 0)
        output += time.Seconds + " 秒";
    return output.Trim();
}

或者使用这个简洁版本:

public static string RelativeDate(DateTime theDate)
{
    Dictionary<long, string> thresholds = new Dictionary<long, string>();
    int minute = 60;
    int hour = 60 * minute;
    int day = 24 * hour;
    thresholds.Add(60, "{0} 秒前");
    thresholds.Add(minute * 2, "1分钟前");
    thresholds.Add(45 * minute, "{0} 分钟前");
    thresholds.Add(120 * minute, "1小时前");
    thresholds.Add(day, "{0} 小时前");
    thresholds.Add(day * 2, "昨天");
    thresholds.Add(day * 30, "{0} 天前");
    thresholds.Add(day * 365, "{0} 月前");
    thresholds.Add(long.MaxValue, "{0} 年前");
    long since = (DateTime.Now.Ticks - theDate.Ticks)/10000000;
    foreach (long threshold in thresholds.Keys) 
    {
        if (since < threshold) 
        {
            TimeSpan t = new TimeSpan((DateTime.Now.Ticks - theDate.Ticks));
            return string.Format(thresholds[threshold], (t.Days > 365 ? t.Days/365 : (t.Days > 0 ? t.Days : (t.Hours > 0 ? t.Hours : (t.Minutes > 0 ? t.Minutes : (t.Seconds > 0 ? t.Seconds : 0))))).ToString());
        }
    }
    return "";
}
日期:2020-03-23 10:15:00 来源:oir作者:oir