2011-03-14 15 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