2011-08-09 38 views
14

爲什麼String.Format("/")轉換爲「 - 」?爲什麼String.Format將正斜槓轉換爲負號?

+5

堆棧溢出社區是免費的,並鼓勵他們盡最大努力改善問題。如果你對此不舒服,Stack Overflow可能不適合你。請儘早參閱[FAQ](http://stackoverflow.com/faq)。 –

回答

21

我懷疑您在{0}佔位符內使用/符號。它是在給定的文化中用作日期時間分隔符的保留符號。你可以這樣逃避它:

string date = string.Format("{0:dd\\/MM\\/yyyy}", DateTime.Now); 
1

它看起來像你的文化中的日期分隔符是「 - 」而不是「/」。看到msdnarticle

編輯:

你檢查你的區域和語言設置,以確保您沒有使用所選的選項「 - 」。

enter image description here

+0

我的短日期格式是'yyyy-MM-dd',但'String.Format(「/」)'仍然返回'「/」'。 – Guffa

+0

@Guffa - 有趣......看起來我在吼叫錯了樹 –

6

我嘗試了所有可能的文化:

foreach (CultureInfo info in CultureInfo.GetCultures(CultureTypes.AllCultures)) { 
    Console.Write(String.Format(info, "/")); 
} 

輸出:

//////////////////////////////////////////////////////////////////////////////// 
//////////////////////////////////////////////////////////////////////////////// 
//////////////////////////////////////////////////////////////////////////////// 
//////////////////////////////////////////////////////////////////////////////// 
////////////////////////////////// 

所以,這不會發生在任何地方。

+0

哈哈,喜歡輸出 – SwDevMan81

13

根據Custom Date and Time Format Strings/是指培養物的日期分隔符。所以你需要逃避它。你可以按Darin的答案使用反斜槓,也可以用單引號引用它。例如:

using System; 
using System.Globalization; 

class Test 
{ 
    static void Main() 
    { 
     DateTime date = DateTime.Now; 

     CultureInfo da = new CultureInfo("da"); 
     // Prints 09-08-2011 
     Console.WriteLine(string.Format(da, "{0:dd/MM/yyyy}", date)); 
     // Prints 09/08/2011 
     Console.WriteLine(string.Format(da, "{0:dd'/'MM'/'yyyy}", date)); 
     // Prints 09/08/2011 
     Console.WriteLine(string.Format(da, "{0:dd\\/MM\\/yyyy}", date)); 
    } 
} 
相關問題