Ho una classe con 2 proprietà data: FirstDay
e LastDay
. LastDay
è annullabile. Vorrei generare una stringa nel formato "x year(s) y day(s)"
. Se gli anni totali sono inferiori a 1, vorrei omettere la sezione dell'anno. Se i giorni totali sono inferiori a 1, vorrei omettere la sezione del giorno. Se uno o due anni sono 0, dovrebbero dire rispettivamente "giorno/anno", anziché "giorni/anni".Formato A TimeSpan con anni
Esempi:
2,2 anni: "2 anni 73 giorni"
1,002,738 mila anni: "1 anno 1 giorno"
0,2 anni : "73 giorni"
2 anni: "2 anni"
Quello che io ho le opere, ma è long:
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;
}
}
Esiste un modo più conciso per farlo (ma comunque leggibile)?
http://codereview.stackexchange.com/ – Kashif