什么是从 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/