我正在开发一个可以在世界上许多国家看到的应用程序。没有多少国家/地区显示小时,分钟和秒以及其他内容:作为分隔符,但有一些,我想确保为其所在地区正确格式化时间。 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小时。