У меня есть класс с двумя свойствами даты: FirstDay
и LastDay
. LastDay
является нулевым. Я хотел бы сгенерировать строку в формате "x year(s) y day(s)"
. Если всего лет меньше 1, я хотел бы опустить раздел года. Если общее количество дней меньше 1, я бы хотел пропустить раздел дня. Если ни годы, ни дни равны 0, они должны сказать "день/год", а не "дни/годы" соответственно.
<сильные > Примеры:
2,2 года: "2 года 73 дня"
1.002738 лет: "1 год 1 день"
0,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;
}
}
Есть ли более краткий способ сделать это (но все еще читаемый)?