c# - 使用asp.net计算时间跨度

标签 c# asp.net .net-3.5

Possible Duplicate:
How do I calculate relative time?

我想使用 asp.net c# 来计算文件上传的时间跨度。例如,如果我两周前上传了一个文件,我的文字会显示“2 周前上传”,或者如果我 4 个月前上传了一个文件,我的文字会显示“4 个月前上传”

任何人都可以给我一些关于如何解决这个问题的提示吗?

谢谢

最佳答案

我遇到了这个问题并创建了 TimeSpan 扩展类,如下所示。

对于使用,您只需在 TimeSpan 实例上使用 ToFriendlyString() 即可。

public static class TimeSpanExtensions
{
    public static string ToFriendlyString(this TimeSpan t)
    {
        return ToFriendlyString(t, Thread.CurrentThread.CurrentCulture);
    }

    public static string ToFriendlyString(this TimeSpan t, CultureInfo cultureInfo)
    {
        if(cultureInfo.IetfLanguageTag.StartsWith("en"))
        {
            return ToFriendlyString_English(t);
        }
        else
        {
            throw new NotSupportedException("This culture is currently not supported.");
        }
    }

    private static string ToFriendlyString_English(TimeSpan t)
    {
        int years = t.Days/365;
        int months = t.Days/30;
        int weeks = t.Days/7;

        if (years > 0) 
        {
            return string.Format("{0} year{1}", years, years > 1 ? "s" : "");
        }
        if (months > 0)
        {
            return string.Format("{0} month{1}", months, months > 1 ? "s" : "");
        }
        if (weeks > 0)
        {
            return string.Format("{0} week{1}", weeks, weeks > 1 ? "s" : "");
        }
        if (t.Days > 0)
        {
            return string.Format("{0} day{1}", t.Days, t.Days > 1 ? "s" : "");
        }
        if (t.Hours > 0)
        {
            return string.Format("{0} hour{1}", t.Hours, t.Hours > 1 ? "s" : "");
        }
        if (t.Minutes > 0)
        {
            return string.Format("{0} minute{1}", t.Minutes, t.Minutes > 1 ? "s" : "");
        }
        if (t.Seconds > 0)
        {
            return string.Format("{0} second{1}", t.Seconds, t.Seconds > 1 ? "s" : "");
        }
        return "now";
    }
}

关于c# - 使用asp.net计算时间跨度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3985828/

相关文章:

c# - 在 WCF 中使用 ConcurrencyMode.Multiple 的优点和缺点

c# - 在 ASP.NET Web 窗体中对特定 URL 启用 CORS

asp.net - .NET 4.5 WebForms : do I (still) really have to specify all 3 templates in a FormView?

mysql - 使用 Entity Framework 查看并插入外部参照表?

c# - 如何在Web服务中使用WSDL生成的代理类?

c# - Xamarin.Forms 实现 AndHud 和 BTProgressHud

c# - Razor 声明性助手条件属性 - 带空格的类不起作用

c# - 了解 IEnumerable - IEnumerator 逻辑

c# - ASP.NET 路由 - 带数据库查找的路由约束

c# - WPF WebBrowser (3.5 SP1) Always on top - 在 WPF 中显示 HTML 的其他建议