2012-07-25 121 views
0

只是好奇... 所以我得到,如果我將日期的字符串版本轉換爲DateTime對象,並將其傳遞到String.Format()方法,然後我「會得到想要的結果。格式化字符串日期與String.Format()

String.Format("The date is {0:MMMM dd, yyyy}", DateTime.Parse("05-22-2012")); 

「的日期是2012年5月22日」

但是,爲什麼不這項工作?

String.Format("The date is {0:MMMM dd, yyyy}", "05-22-2012") 

「的日期是05-22-2012 「

很抱歉,如果這是一個愚蠢的問題,但我只是想了解如何工作的。 感謝

回答

3

其他這裏的答案觸及了顯着的poi NTS,但讓我們把它們放在一起的研究如何String.Format作品。

它有五個重載,但我們只談談它們都重定向到的一個(這不是實際的代碼,如果你想用Reflector或ILSpy查看它,你會發現它在StringBuilder.AppendFormat )。爲了便於理解,這被簡化了。

public static string Format(IFormatProvider provider, string format, params object[] args) 
{ 
    StringBuilder sb = new StringBuilder(); 

    // Break up the format string into an array of tokens 
    Token[] tokens = ParseFormatString(format); 

    foreach (Token token in tokens) 
    { 
     switch (token.TokenType) 
     { 
      // A Text token is just some text to output directly 
      case TokenType.Text: 
       sb.Append(token.Text); 
       break; 

      // An Index token represents something like {0} or {2:format} 
      // token.Index is the argument index 
      // token.FormatText is the format string inside ('' in the first example, 'format' in the second example) 
      case TokenType.Index: 
       { 
        object arg = args[token.Index]; 

        IFormattable formattable = arg as IFormattable; 
        if (formattable != null && token.FormatText.Length > 0) 
        { 
         // If the argument is IFormattable we pass it the format string specified with the index 
         sb.Append(formattable.ToString(token.FormatText, provider)); 
        } 
        else 
        { 
         // Otherwise we just use Object.ToString 
         sb.Append(arg.ToString()); 
        } 
       } 
       break; 
     } 
    } 

    return sb.ToString(); 
} 

在你的問題中,你問爲什麼格式字符串不適用,當你通過「05-22-2012」。正如Guffa所說,這不是一個DateTime對象,它是一個String對象。

正如GSerjo說,一個字符串不是IFormattable。字符串不是格式化的,因爲格式化是將某些東西轉換爲字符串的過程。一個字符串已經是一個字符串!

所以你可以看到,當Format方法進入索引器時,arg將不會IFormattable,它將簡單地調用ToString。對字符串調用ToString只是返回自己,它已經是一個字符串了。總之,如果你的格式字符串包含一個帶有內格式字符串(例如{0:格式})的索引,那麼只有當相關參數是IFormattable並且它知道該做什麼時才應用該內格式字符串用你給它的格式字符串。

+0

這真的給我帶來了很好的解釋。謝謝! – Dmase05 2012-07-26 02:17:30

2

自定義日期時間格式只能在一個DateTime值。如果您使用的是字符串,則該格式將被忽略,因爲只有一種方法可以輸出字符串。

+0

絕對有意義,謝謝 – Dmase05 2012-07-26 02:13:19