假设我有678天,如何计算从那一刻起有多少年,几个月和几天?
Duration duration = Duration.FromStandardDays(678);
Instant now = SystemClock.Instance.Now;
Instant future = now + duration;
// I have to convert NodaTime.Instant to NodaTime.LocalDate but don't know how
Period period = Period.Between(now, future);
Console.WriteLine("{0} years, {1} months, {2} days", period.Years, period.Months, period.Days);
Run Code Online (Sandbox Code Playgroud)
你可以用Noda Time做到这一点.
首先,你需要一个起点.这使用当地时区的当前日期.您可能希望使用不同的日期或不同的时区,具体取决于您的方案.
Instant now = SystemClock.Instance.Now;
DateTimeZone timeZone = DateTimeZoneProviders.Bcl.GetSystemDefault();
LocalDate today = now.InZone(timeZone).Date;
Run Code Online (Sandbox Code Playgroud)
然后只需添加天数:
int days = 678;
LocalDate future = today.PlusDays(days);
Run Code Online (Sandbox Code Playgroud)
然后,您可以获得所需单位的期间:
Period period = Period.Between(today, future, PeriodUnits.YearMonthDay);
Console.WriteLine("{0} years, {1} months, {2} days",
period.Years, period.Months, period.Days);
Run Code Online (Sandbox Code Playgroud)
重要的是要认识到结果代表"从现在起的时间".或者,如果您替换不同的起点,那就是"从(起点)开始的时间 ".在任何情况下你都不应该只考虑结果X days = Y years + M months + D days.这将是毫无意义的,因为天在一年的数量和在一个月的天数取决于它你谈的年份和月份.
您只需将天数添加到当前时间即可:
var now = DateTime.Now;
var future = now.AddDays(678);
int years = future.Year - now.Year;
int months = future.Month - now.Month;
if (months < 0)
{
years--;
months += 12;
}
int days = future.Day + DateTime.DaysInMonth(now.Year, now.Month) - now.Day;
Run Code Online (Sandbox Code Playgroud)