c# - 将时间转换为易于阅读的字符串

标签 c# sql-server datetime

什么是从 sql server 获取日期时间并将其转换为使用友好字符串的最佳方法,如下所示:

如果超过 1 天 > 1 天前。
超过 7 天 > 1 周前
1年前
3分钟前
56 秒前。

等这可以轻松完成吗?

最佳答案

最好的办法是制作一个DateTime 扩展方法:

public static class DateTimeExtensions
{
    public static string ToRelative(this DateTime value)
    {        
        DateTime now = DateTime.Now; //maybe UtcNow if you're into that

        TimeSpan span = new TimeSpan(now.Ticks - value.Ticks);
        double seconds = Math.Abs(ts.TotalSeconds);

        if (seconds < 60)
            return string.Format("{0} seconds ago", span.Seconds);

        if (seconds < 2700)
            return string.Format("{0} minutes ago", span.Minutes);

        if (seconds < 86400)
            return string.Format("{0} hours ago", span.Hours);

        // repeat for greater "ago" times...
    }
}

然后调用您的 DateTime 值,如下所示:

myDateTime.ToRelative();

关于c# - 将时间转换为易于阅读的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13805390/

相关文章:

datetime - VB6 日期数据类型 : precision and formatting

c# - 如何使字段在运行时可编辑

c# - 程序不应尝试从哪些异常中恢复?

c# - Monotouch IPA 替换在同一台计算机上签名的另一个应用程序

sql - 在这种情况下我应该如何工作。我应该使用触发器还是保留用户来管理

sql - 如何在另一个存储过程中使用存储过程的结果?

javascript - D3v4 : d3. timeParse 失败,UNIX 纪元秒 (%s)

c# - 如何编写以下 group by 和剥离时间的 Linq 查询?

c# - 使 Entity Framework 不区分大小写

SQL 序列在 case 语句中使用时跳过值