TimeSpan“美好时光” C# 中的格式
输入此问题的标题使我看到此问题。我正在寻找同样的东西,但是如果你明白我的意思的话,可能是不太静态格式的东西?
我正在编写一个快速程序,它将获取两个 DateTime 对象的 TimeSpan 持续时间并将它们输出以打印到纸张上。
首选格式是:XX 天,YY 小时,ZZ 分钟
(秒是无关紧要的;天也是如此,因为我预计时间跨度不会超过几个小时) .
说出以下代码(作为示例):
DateTime start = DateTime.Now;
DateTime end = DateTime.Now.AddMinutes(135);
TimeSpan duration = (end - start);
// output duration as XX hours, YY minutes
谢谢,
扎克
P.S. 我还遇到了“PrettyTime.NET”,但它输出了诸如“3天前”之类的内容等等。我在 google 上发现的用于格式化持续时间字符串的每个其他主题(如上面的示例)都引导我找到基于 Java 的解决方案。 :\
更新 2014-09-08:
为了 3 年后的跟进,我在 NuGet 和 Github 上找到了一个很棒的库,名为“Humanizer" 这可以解决我遇到的这个问题。我没怎么用过它,但我确实尝试过,而且效果很好。不过,它是一个相当大的库(它会向项目的构建路径发出大量不同文化的文件夹(我确信有一种方法可以自定义它))。
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?
I'm writing a quick program that will be taking a TimeSpan duration of two DateTime objects and outputting them for printing to paper.
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
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. :\
UPDATE 2014-09-08:
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)).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你关心多元化:
And if you care about pluralization:
你可以直接输出:
如果你要处理“短”时间,并且你希望它更干净,你可以这样做:
You can just output this directly:
If you are going to be handling "short" times, and you want this to be cleaner, you could do something like:
使用 C# 7:
With C# 7: