2010-01-26 27 views
2

可能重複:
Fuzzy date algorithm
How do I calculate relative time?格式的DateTime像計算器

嗨,

如何,格式化日期時間像這樣?

1分鐘前

1小時前

問08月15日15:00

+0

看這裏http://stackoverflow.com/questions/822124/fuzzy-date-algorithm – 2010-01-26 11:28:52

+0

當前datetime-post datetime。然後基於秒,分,小時格式化字符串? – RvdK 2010-01-26 11:29:08

+6

甚至更​​早:http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time – Oded 2010-01-26 11:31:56

回答

2

您需要做的第一件事是確定日期的差異。

DateTime上使用減法()方法。它返回TimeSpan,這對您的需求很方便。

TimeSpan mySpan = DateTime.Now.Subtract(myPostedDate); 

然後,您需要找到最重要的非零時間元素。如果你處理日子,事情很簡單。較小的教派需要更多的工作。包括代碼。

TimeSpan mySpan = DateTime.Now.Subtract(myRecorded); 
string myDenom = 
    mySpan.Days > 0 ? "day" : 
    mySpan.Hours > 0 ? "hour" : 
    mySpan.Minutes > 0 ? "minute" : "second"; 

string myOutput = String.Empty; 

int myNumeral; 

// if we're dealing with days, a format string will suffice 
if (myDenom == "day") 
{ 
    // HH - 24 hour clock 
    myOutput = String.Format("{0:MMM dd} at {0:HH}:{0:mm}", myRecorded); 
} 
else 
{ 
    // put the right denomination into myNumeral 
    switch (myDenom) 
    { 
     case "second": 
      myNumeral = mySpan.Seconds; 
      break; 
     case "minute": 
      myNumeral = mySpan.Minutes; 
      break; 
     default: 
      myNumeral = mySpan.Hours; 
      break; 
    } 

    // add an s to myNumeral when > 1 
    myDenom += (myNumeral > 1) ? "s" : String.Empty; 
    myOutput = String.Format("{0} {1} ago", myNumeral, myDenom); 
} 

// myOutput now contains formatted string