2011-03-08 102 views
5

是否有一種簡單的方法顯示日期的第一天,第二天,第三天......的日期部分?我懷疑沒有辦法通過自定義日期時間格式字符串(我會很高興出錯),所以有誰實現了這樣做?格式化日期時間值日期值

+0

哪些語言和.NET版本您使用的? – Vishal 2011-03-08 17:45:00

+0

相關:http://stackoverflow.com/questions/20156/is-there-an-easy-way-to-create-ordinals-in-c – StriplingWarrior 2011-03-08 17:49:31

+0

@Misnomer - 目前使用.net 3.5。我將以任何.Net語言接受答案。 – detaylor 2011-03-08 17:53:00

回答

9

這是實現這一目標的核心邏輯:

string SuffixForDay(DateTime date) { 
    switch (date.Day) { 
     case 1: 
     case 21: 
     case 31: 
      return "st"; 
     case 2: 
     case 22: 
      return "nd"; 
     case 3: 
     case 23: 
      return "rd"; 
     default: 
      return "th"; 
    } 
} 
+0

+1 - 對於簡單的代碼..(和以前評論我的刪除答案!) – Vishal 2011-03-08 18:10:25

0

您可以使用DateTime.Day屬性來達到此目的。

+0

...並寫代碼動態地添加後綴:st,nd,rd,th(好像只有4個例子) – Cosmin 2011-03-08 17:50:37

+0

一天只返回整數值而不是後綴「st」,「rd」,「th 「etc – detaylor 2011-03-08 17:51:14