时间跨度友好字符串库(C#) [英] TimeSpan to friendly string library (C#)

查看:171
本文介绍了时间跨度友好字符串库(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁将为时间跨度对象转换为友好的字符串,如知道一个很好的库(或代码片段)的:

Does anyone know of a good library (or code snippet) for converting a TimeSpan object to a "friendly" string such as:


  • 两年三个月四天

  • 一周两天

(这是为一个文件有效期制度,在期满可以从几天什么几十年)

(It's for a document expiry system, where the expiry could be anything from a few days to several decades)

只是为了澄清,说我有一个时间跨度为7天,即应打印1周,14天2周,366天1年和1天,等等等等。

Just to clarify, say I had a TimeSpan with 7 days, that should print "1 week", 14 days "2 weeks", 366 days "1 year and 1 day", etc etc.

推荐答案

不是一个完整的实现,但它应该让你足够接近

Not a fully featured implementation, but it should get you close enough.

DateTime dtNow = DateTime.Now;
DateTime dtYesterday = DateTime.Now.AddDays(-435.0);
TimeSpan ts = dtNow.Subtract(dtYesterday);

int years = ts.Days / 365; //no leap year accounting
int months = (ts.Days % 365) / 30; //naive guess at month size
int weeks = ((ts.Days % 365) % 30) / 7;
int days = (((ts.Days % 365) % 30) % 7);

StringBuilder sb = new StringBuilder();
if(years > 0)
{
    sb.Append(years.ToString() + " years, ");
}
if(months > 0)
{
    sb.Append(months.ToString() + " months, ");
}
if(weeks > 0)
{
    sb.Append(weeks.ToString() + " weeks, ");
}
if(days > 0)
{
    sb.Append(days.ToString() + " days.");
}
string FormattedTimeSpan = sb.ToString();

在最后,你真的需要让别人知道一个文件即将过期准确1年5个月,2周,3天从现在开始?你能不能跟告诉他们该文件会从现在起1年以上到期从现在起,或通过5个月度日?只取最大的单位,说在该单位的n个。

In the end, do you really need to let someone know a document is going to expire exactly 1 year, 5 months, 2 weeks, and 3 days from now? Can't you get by with telling them the document will expire over 1 year from now, or over 5 months from now? Just take the largest unit and say over n of that unit.

这篇关于时间跨度友好字符串库(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆