2011-03-14 16 views
13

可能重复:
How do I calculate relative time?asp.net的MVC前段时间文字帮手

有什么相似的轨道time_ago_in_words帮手asp.net MVC?

+0

很难确定,因为我没有亲自使用rails或他指的助手,但是基于文档中的[context](http://bit.ly/h7zYCS),它看起来很相似到ASP.NET MVC中的HtmlHelper。话虽如此,我不相信这是重复的。是的,建议重复中的代码可以工作,但这纯粹是服务器端方法。所需的输出不需要在服务器端生成,因此我提供的与复本不同的答案仍然适用。 **不要关闭这个问题**。 – 2011-03-14 19:08:32

+1

包括['time_ago_in_words'](http://apidock.com/rails/ActionView/Helpers/DateHelper/time_ago_in_words)如何运作的细节可能会帮助人们有效回答这个问题。包括你*想要使用它的细节将会*甚至更好*。 – Shog9 2011-03-14 19:23:18

+0

这真的不应该被关闭...... *请投票重新打开。* – 2011-03-15 17:28:58

回答

23

根据您的预期输出目标,jQuery插件Timeago可能是更好的选择。

这里有一个对的HtmlHelper创建包含ISO 8601时间戳的<abbr />元素:

public static MvcHtmlString Timeago(this HtmlHelper helper, DateTime dateTime) { 
    var tag = new TagBuilder("abbr"); 
    tag.AddCssClass("timeago"); 
    tag.Attributes.Add("title", dateTime.ToString("s") + "Z"); 
    tag.SetInnerText(dateTime.ToString()); 

    return MvcHtmlString.Create(tag.ToString()); 
} 

结合上述辅助输出与以下JavaScript某处您的网页上,你会在金钱。

<script src="jquery.min.js" type="text/javascript"></script> 
<script src="jquery.timeago.js" type="text/javascript"></script> 

jQuery(document).ready(function() { 
    jQuery("abbr.timeago").timeago(); 
}); 
+0

如果我传递一个dateTime.ToUniversal()日期,timeago会正确计算相对时间,但工具提示会显示UTC时区而不是客户端的时间电脑时区。我错过了什么? – emzero 2014-03-14 02:11:51

+0

我真的很喜欢这个,谢谢!我认为尽管在'SetInnerText'中,日期的原始输出可能会更友好,我会改变它,以便降级很好。 – Luke 2014-10-06 09:32:48

18

我正在使用以下扩展方法。不知道这是否是最好的。

public static string ToRelativeDate(this DateTime dateTime) 
{ 
    var timeSpan = DateTime.Now - dateTime; 

    if (timeSpan <= TimeSpan.FromSeconds(60)) 
     return string.Format("{0} seconds ago", timeSpan.Seconds); 

    if (timeSpan <= TimeSpan.FromMinutes(60)) 
     return timeSpan.Minutes > 1 ? String.Format("about {0} minutes ago", timeSpan.Minutes) : "about a minute ago"; 

    if (timeSpan <= TimeSpan.FromHours(24)) 
     return timeSpan.Hours > 1 ? String.Format("about {0} hours ago", timeSpan.Hours) : "about an hour ago"; 

    if (timeSpan <= TimeSpan.FromDays(30)) 
     return timeSpan.Days > 1 ? String.Format("about {0} days ago", timeSpan.Days) : "yesterday"; 

    if (timeSpan <= TimeSpan.FromDays(365)) 
     return timeSpan.Days > 30 ? String.Format("about {0} months ago", timeSpan.Days/30) : "about a month ago"; 

    return timeSpan.Days > 365 ? String.Format("about {0} years ago", timeSpan.Days/365) : "about a year ago"; 
} 

助手应该是财产以后这样的:

public MvcHtmlString Timeago(this HtmlHelper helper, DateTime dateTime) 
{ 
    return MvcHtmlString.Create(dateTime.ToRelativeDate()); 
} 

希望它能帮助!

+3

小挑逗,你有这个函数的多元化错误 – 2013-02-11 17:42:14