2009-10-14 44 views
6

有沒有人有簡單的函數來將日期轉換爲簡單的字符串(使用.Net)?.Net中簡單文本的日期(例如,今天,昨天,1周前)

E.g. 10月14日 - 09會讀 「今天」,10月13日09會讀 「昨天」 和7-OCT-09將改爲 「1周前」 等等

乾杯, 添

+0

有趣的拿。我不確定你會得到任何超出「滾動你自己」的答案:) – JustLoren

+4

本網站的第一個問題之一處理了這個問題:http://stackoverflow.com/questions/11/how- do-i-calculate-relative-time –

+0

並且爲了實現SQL中的這種方式(您是否曾經想過):http://stackoverflow.com/questions/50149/best-way-to-convert-datetime-to -n-hours-ago-in-sql – CraigTP

回答

6

你確實要用自己的方法來做這個,就像JustLoren說的那樣。

這是我一直在使用的擴展方法。腳本製作成擴展方法是GateKiller。所以充分信任他。你可以很容易地將其改變爲你想要的。

public static string ToTimeSinceString(this DateTime value) 
{ 
    const int SECOND = 1; 
    const int MINUTE = 60 * SECOND; 
    const int HOUR = 60 * MINUTE; 
    const int DAY = 24 * HOUR; 
    const int MONTH = 30 * DAY; 

    TimeSpan ts = new TimeSpan(DateTime.Now.Ticks - value.Ticks); 
    double seconds = ts.TotalSeconds; 

    // Less than one minute 
    if (seconds < 1 * MINUTE) 
     return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago"; 

    if (seconds < 60 * MINUTE) 
     return ts.Minutes + " minutes ago"; 

    if (seconds < 120 * MINUTE) 
     return "an hour ago"; 

    if (seconds < 24 * HOUR) 
     return ts.Hours + " hours ago"; 

    if (seconds < 48 * HOUR) 
     return "yesterday"; 

    if (seconds < 30 * DAY) 
     return ts.Days + " days ago"; 

    if (seconds < 12 * MONTH) { 
     int months = Convert.ToInt32(Math.Floor((double)ts.Days/30)); 
     return months <= 1 ? "one month ago" : months + " months ago"; 
    } 

    int years = Convert.ToInt32(Math.Floor((double)ts.Days/365)); 
    return years <= 1 ? "one year ago" : years + " years ago"; 
} 
+0

這似乎直接來自我在問題評論中鏈接到的問題的接受答案; o) –

+0

真的很抱歉。我忘記了它來自哪裏。增加了信譽來回答。 – aolde

+0

太好了,謝謝!爲我節省了一些時間:) – TimS

6

像這樣的擴展方法?

public static string Stringfy(this DateTime date) 
{ 
    if ((DateTime.Now - date.Date).TotalDays == 0) 
     return "Today"; 

    if ((DateTime.Now - date.Date).TotalDays == 1) 
     return "Yesterday"; 

    // ... 

    return "A long time ago, in a galaxy far far away..."; 
} 
+3

+1對於遙遠的星系 – Phil

+0

是不是TotalDays是雙重的?也許截斷是爲了獲得整天,甚至使用DateTime.Now.Date而不是DateTime.Now – Darren

相關問題