2012-10-02 36 views
7

我正在研究一個可能在世界上許多國家/地區可以看到的應用程序。沒有多少國家可以顯示小時,分鐘和秒鐘以外的其他內容:作爲分隔符,但有幾個國家,我想確保時間格式正確的地區。 DateTime在這方面很出色,但TimeSpan不是。這些片段來自Visual Studio 2010中使用.Net 4的立即窗口,其中我的區域設置爲Malayalam(印度)。 dateTime.Now調用還反映了我的時鐘,Microsoft Outlook和其他區域的時間顯示情況。格式化不同文化中的TimeSpan

DateTime.Now.ToString() 
"02-10-12 17.00.58" 

http://msdn.microsoft.com/en-us/library/dd784379.aspx說「如果formatProvider爲空,將使用與當前區域性關聯的DateTimeFormatInfo對象。如果格式是一個自定義格式字符串,則formatProvider參數被忽略。」當然,我不應該需要傳遞Current CultureInfo。我在這裏想要的格式是hh.mm.ss,但是在大多數其他語言中顯而易見的是:mm:ss,並且如果還有其他的可能性,它也應該自動反映這些格式 - 基本上TimeSpan 應該是文化意識,只是因爲DateTime是。

但是:

timeRemaining.ToString() 
"00:02:09" 
timeRemaining.ToString("c") 
"00:02:09" 
timeRemaining.ToString("c", CultureInfo.CurrentCulture) 
"00:02:09" 
timeRemaining.ToString("g") 
"0:02:09" 
timeRemaining.ToString("G") 
"0:00:02:09.0000000" 
timeRemaining.ToString("t") 
"00:02:09" 
timeRemaining.ToString("g", CultureInfo.CurrentCulture) 
"0:02:09" 
timeRemaining.ToString("g", CultureInfo.CurrentUICulture) 
"0:02:09" 
timeRemaining.ToString("G", CultureInfo.CurrentUICulture) 
"0:00:02:09.0000000" 
timeRemaining.ToString("G", CultureInfo.CurrentCulture) 
"0:00:02:09.0000000" 
timeRemaining.ToString("t", CultureInfo.CurrentCulture) 
"00:02:09" 

我在尋找一個簡單的,單一線路輸出文化的感知方式的時間跨度。任何想法都表示讚賞。

回答

4

看起來像一個錯誤,你可以在connect.microsoft.com上報告它。同時,解決方法是利用DateTime格式。就像這樣:

using System; 
using System.Globalization; 

class Program { 
    static void Main(string[] args) { 
     var ci = CultureInfo.GetCultureInfo("ml-IN"); 
     System.Threading.Thread.CurrentThread.CurrentCulture = ci; 
     var ts = new TimeSpan(0, 2, 9); 
     var dt = new DateTime(Math.Abs(ts.Ticks)); 
     Console.WriteLine(dt.ToString("HH:mm:ss")); 
     Console.ReadLine(); 
    } 
} 

輸出:

00.02.09

+0

但是,如果要使用格式字符串,則更簡單的解決方法是'ts.ToString(「h'。'mm'。'ss」)'。從.NET 4.0開始工作。這硬編碼的時期。如果你想使用文化的時間分隔符,可以從'CultureInfo.CurrentCulture.DateTimeFormat.TimeSeparator'中讀取它,把它放在撇號中,並與格式字符串中的'h','mm'和'ss'一起使用'TimeSpan'。 –

+3

很難看出這是「更簡單」。這樣的代碼忽略時間格式會覆蓋控制面板中指定的用戶,這肯定是不準確的。 –

1

這更像是一個評論,但需要一定的空間,所以我寫它作爲一個答案。

儘管字符串格式爲DateTime已經在.NET中使用了很長時間,但是在.NET 4.0(Visual Studio 2010)中,TimeSpan的格式是新增的。

的培養有一個用來通過DateTime幷包括關於是否使用結腸:或週期.或小時,分鐘和秒之間別的東西信息一個DateTimeFormatInfo對象。現在,TimeSpan似乎沒有使用這個DateTimeFormatInfo對象,並且沒有什麼叫「TimeSpanFormatInfo」。

下面是一個例子:

// we start from a non-read-only invariant culture 
Thread.CurrentThread.CurrentCulture = new CultureInfo(""); 

// change time separator of DateTime format info of the culture 
CultureInfo.CurrentCulture.DateTimeFormat.TimeSeparator = "<-->"; 

var dt = new DateTime(2013, 7, 8, 13, 14, 15); 
Console.WriteLine(dt); // writes "07/08/2013 13<-->14<-->15" 

var ts = new TimeSpan(13, 14, 15); 
Console.WriteLine(ts); // writes "13:14:15" 
1

我在尋找一個簡單的,單一線路輸出文化的感知方式的時間跨度。

那麼我認爲你最好使用DateTime類做的格式爲您提供:

string display = new DateTime(timespan.Ticks).ToLongTimeString(); 

假設timespan保持爲0至24小時的超長之間存在正的持續時間。