时间跨度"相当的时间和QUOT;在C#中的格式 [英] TimeSpan "pretty time" format in C#
问题描述
打字的称号对这个问题给我带来了这个问题。我在寻找同样的事情,但事情可能不太静态格式,如果你明白我的意思?
Typing in the title to this question brought me to this question. I'm looking for the same thing, but something perhaps less statically formatted if you get what I mean?
我在写一个快速程序,将采取一个时间跨度两个datetime对象的持续时间并输出打印到纸张
I'm writing a quick program that will be taking a TimeSpan duration of two DateTime objects and outputting them for printing to paper.
将是首选的格式为: XX天,YY小时,ZZ分钟
(秒是不相关的,因为是天,因为我不希望这个时间跨度纳入超过几个小时以上)。
The format that would be preferred is: XX days, YY hours, ZZ minutes
(seconds are irrelevant; as are days because I don't expect the timespan to incorporate more than a few hours).
说出下面的代码(作为一个例子):
Say the following code (as an example):
DateTime start = DateTime.Now;
DateTime end = DateTime.Now.AddMinutes(135);
TimeSpan duration = (end - start);
// output duration as XX hours, YY minutes
谢谢,
扎克
Thanks,
Zack
PS
我也跑过 PrettyTime.NET ,但它输出像 4天前等,每隔话题我在谷歌找到像上面的例子使我一个基于Java的解决方案格式化持续时间字符串。 :\
P.S. I also ran across "PrettyTime.NET", but it output things like "3 days ago", etc. Every other topic I found on google to format time duration strings like the above examples lead me to a Java-based solution. :\
更新2014年9月8日:
要随访3年后,我发现上的NuGet和Github上被称为的 Humanizer ,这将解决这个问题,我有。我没有用它那么多,但我没有尝试它和它精美的作品。这是相当大的一个图书馆,虽然(它发出一个整体每吨不同的文化到项目的构建路径的文件夹(我敢肯定有向定制)的方式)。
To follow-up after 3 years, I've found an awesome library on NuGet and Github called "Humanizer" which would solve this issue I was having. I haven't used it that much, but I did try it and it works beautifully. It's quite large of a library though (it emits a whole ton of folders for different cultures to your project's build path (I'm sure there's a way to to customize it)).
推荐答案
如果你在乎多元化:
public static string ToPrettyFormat(this TimeSpan span) {
if (span == TimeSpan.Zero) return "0 minutes";
var sb = new StringBuilder();
if (span.Days > 0)
sb.AppendFormat("{0} day{1} ", span.Days, span.Days > 1 ? "s" : String.Empty);
if (span.Hours > 0)
sb.AppendFormat("{0} hour{1} ", span.Hours, span.Hours > 1 ? "s" : String.Empty);
if (span.Minutes > 0)
sb.AppendFormat("{0} minute{1} ", span.Minutes, span.Minutes > 1 ? "s" : String.Empty);
return sb.ToString();
}
这篇关于时间跨度"相当的时间和QUOT;在C#中的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!