以下代码
Console.WriteLine("{0:%h} hours {0:%m} minutes",
new TimeSpan(TimeSpan.TicksPerDay));
产生这个输出:
0 hours 0 minutes
我想要的是这个输出:
24 hours 0 minutes
我在这个格式字符串中遗漏了什么?
附:我知道我可以手动将 TimeSpan 分解为天和小时,然后将两者相乘,但宁愿使用自定义格式字符串,因为这些时间跨度显示在 silverlight 数据网格中,人们希望看到的是 horus,而不是天。
最佳答案
根据MSDN , 使用 %h
会告诉你
The number of whole hours in the time interval that are not counted as part of days.
我认为您需要使用 TimeSpan
类的 TotalHours
属性,例如:
TimeSpan day= new TimeSpan(TimeSpan.TicksPerDay);
Console.WriteLine("{0} hours {1} minutes", (int)day.TotalHours, day.Minutes);
更新
如果您绝对需要能够通过将自定义格式化程序传递给 ToString
方法来实现规定的格式,您可能需要创建自己的 CustomTimeSpan
类。不幸的是,您不能从 struct
继承,因此您必须从头开始构建它。
https://stackoverflow.com/questions/5703990/