TimeSpan 和 DateTime 的格式化字符串之间的不同行为
今天编码时,我注意到时间跨度和格式化字符串有些奇怪。我试图打印一个时间跨度,例如将 01:03:37
打印为 1:03:37
(没有前导 0 几个小时)。所以我使用了格式字符串h:mm:ss
。然而,这给了我一个前导 0。如果我将 TimeSpan 转换为 DateTime 并再次执行相同的操作,h
格式化字符串将按我的预期工作。
示例控制台程序:
class Program
{
static void Main(string[] args)
{
var time = new TimeSpan(01, 03, 37);
var culture = new CultureInfo("sv-SE");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
Console.WriteLine(time.ToString());
Console.WriteLine(string.Format(culture, "{0:h:mm:ss}", time));
Console.WriteLine(string.Format(culture, "{0:hh:mm:ss}", time));
Console.WriteLine((new DateTime(time.Ticks)).ToString("h:mm:ss", culture));
Console.WriteLine((new DateTime(time.Ticks)).ToString("hh:mm:ss", culture));
Console.ReadKey();
}
}
输出:
01:03:37
01:03:37 // <-- expected: 1:03:37
01:03:37
1:03:37
01:03:37
为什么 TimeSpan 和 DateTime 的行为不同?
While coding today, I noticed something odd with timespans and formatting strings. I was trying to print a timespan, for instance 01:03:37
as 1:03:37
(without the leading 0 for hours). So I used the format string h:mm:ss
. This, however, gave me a leading 0. If I converted the TimeSpan to a DateTime and did the same thing again, the h
formatting string worked as I expected.
A sample console program:
class Program
{
static void Main(string[] args)
{
var time = new TimeSpan(01, 03, 37);
var culture = new CultureInfo("sv-SE");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
Console.WriteLine(time.ToString());
Console.WriteLine(string.Format(culture, "{0:h:mm:ss}", time));
Console.WriteLine(string.Format(culture, "{0:hh:mm:ss}", time));
Console.WriteLine((new DateTime(time.Ticks)).ToString("h:mm:ss", culture));
Console.WriteLine((new DateTime(time.Ticks)).ToString("hh:mm:ss", culture));
Console.ReadKey();
}
}
Output:
01:03:37
01:03:37 // <-- expected: 1:03:37
01:03:37
1:03:37
01:03:37
Why is the TimeSpan and DateTime behaving differently?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为您的格式字符串不适用于
TimeSpan
并且TimeSpan.ToString()
始终返回 (来自 MSDN):Because your formatting string do not work for
TimeSpan
andTimeSpan.ToString()
always returns (from MSDN):在 .Net 4.0 之前,TimeSpans 不支持格式字符串。
在 .Net 4.0 中,格式字符串已记录。
Until .Net 4.0, TimeSpans do not support format strings.
In .Net 4.0, the format strings are documented.
查看 http://msdn.microsoft.com/en-us/library/ ee372286.aspx。
Check out http://msdn.microsoft.com/en-us/library/ee372286.aspx.