c# - 用年份格式化 TimeSpan

我有一个具有 2 个日期属性的类:FirstDayLastDayLastDay 可以为空。我想生成 "x year(s) y day(s)" 格式的字符串。如果总年份小于 1,我想省略年份部分。如果总天数小于 1,我想省略天部分。如果年或日为 0,则应分别表示“日/年”,而不是“日/年”。

示例:
2.2 年:             “2 年 73 天”
1.002738 年:   “1 年 1 天”
0.2 年:             “73 天”
2 年:                “2 年”

我有什么作品,但是很长:

private const decimal DaysInAYear = 365.242M;

public string LengthInYearsAndDays
{
    get
    {
        var lastDay = this.LastDay ?? DateTime.Today;
        var lengthValue = lastDay - this.FirstDay;

        var builder = new StringBuilder();

        var totalDays = (decimal)lengthValue.TotalDays;
        var totalYears = totalDays / DaysInAYear;
        var years = (int)Math.Floor(totalYears);

        totalDays -= (years * DaysInAYear);
        var days = (int)Math.Floor(totalDays);

        Func<int, string> sIfPlural = value =>
            value > 1 ? "s" : string.Empty;

        if (years > 0)
        {
            builder.AppendFormat(
                CultureInfo.InvariantCulture,
                "{0} year{1}",
                years,
                sIfPlural(years));

            if (days > 0)
            {
                builder.Append(" ");
            }
        }

        if (days > 0)
        {
            builder.AppendFormat(
                CultureInfo.InvariantCulture,
                "{0} day{1}",
                days,
                sIfPlural(days));
        }

        var length = builder.ToString();
        return length;
    }
}

有没有更简洁的方法来做到这一点(但仍然可读)?

最佳答案

TimeSpan 没有合理的“年”概念,因为它取决于起点和终点。 (月份类似 - 29 天有多少个月?嗯,这取决于...)

给个无耻的插件,我的Noda Time项目使这变得非常简单:

using System;
using NodaTime;

public class Test
{
    static void Main(string[] args)
    {
        LocalDate start = new LocalDate(2010, 6, 19);
        LocalDate end = new LocalDate(2013, 4, 11);
        Period period = Period.Between(start, end,
                                       PeriodUnits.Years | PeriodUnits.Days);

        Console.WriteLine("Between {0} and {1} are {2} years and {3} days",
                          start, end, period.Years, period.Days);
    }
}

输出:

Between 19 June 2010 and 11 April 2013 are 2 years and 296 days

https://stackoverflow.com/questions/15957984/

相关文章:

intellij-idea - 在 PyCharm 中用换行符包装注释

python - 在 Python 中格式化电话号码的最佳方法是什么?

r - 如何删除数字 R 变量中的前导 "0."

sql - 我可以在 DBIx::Class 中漂亮地打印 DBIC_TRACE 输出吗?

r - 如何使用 R 的 sprintf 创建固定宽度的字符串,并在 END 处填充空白?

django - 是否有 django 模板过滤器来显示百分比?

postgresql - 如何将 "1 day 01:30:00"之类的间隔转换为 "25:30:0

html - 在每个标记属性上换行并在 Visual Studio HTML 代码编辑器中保持对齐

c# - 您如何将 { 和 } 放入格式字符串中

javascript - 在 JavaScript 中将十六进制数字格式化为短 UUID