如何以文化感知的方式格式化TimeSpan的HH:mm:ss分隔符?

我正在开发一个可以在世界上许多国家看到的应用程序。 没有多少国家/地区显示小时,分钟和秒钟以外的其他内容:作为分隔符,但有一些,我想确保时区格式正确的区域。 DateTime很棒,但TimeSpan不是。 这些片段来自我在Visual Studio 2010中的即时窗口,使用.Net 4,我的区域设置为Malayalam(印度)。 dateTime.Now调用还反映了我的时钟,Microsoft Outlook和其他领域的时间显示方式。

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

http://msdn.microsoft.com/en-us/library/dd784379.aspx表示“如果formatProvider为null,则使用与当前区域性关联的DateTimeFormatInfo对象。如果format是自定义格式字符串,则为formatProvider参数被忽略了。“ 按理说那我甚至不需要传递当前的CultureInfo。 我想要的格式是hh.mm.ss但是显而易见hh: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" 

我正在寻找一个简单的单行来以文化意识的方式输出timeSpan。 任何想法都表示赞赏。

看起来像一个错误,您可以在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

这更像是一个评论,但需要一些空间,所以我把它写成答案。

虽然DateTime字符串格式已经在.NET中存在了很长时间,但TimeSpan格式化在.NET 4.0(Visual Studio 2010)中是新的。

文化具有DateTimeFormatInfo对象,该对象由DateTime使用,并包含有关是否使用冒号:或句点的信息. 小时,分钟和秒之间的其他东西。 现在, 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" 

我正在寻找一个简单的单行来以文化意识的方式输出timeSpan。

然后我认为你最好使用DateTime类为你做格式化:

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

假设timespan持续0到24小时之间的正持续时间。