假设我有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);
答案 0 :(得分:7)
你可以用Noda Time做到这一点。
首先,你需要一个起点。这使用当地时区的当前日期。您可能希望使用不同的日期或不同的时区,具体取决于您的方案。
Instant now = SystemClock.Instance.Now;
DateTimeZone timeZone = DateTimeZoneProviders.Bcl.GetSystemDefault();
LocalDate today = now.InZone(timeZone).Date;
然后只需添加天数:
int days = 678;
LocalDate future = today.PlusDays(days);
然后您可以获得具有所需单位的句号:
Period period = Period.Between(today, future, PeriodUnits.YearMonthDay);
Console.WriteLine("{0} years, {1} months, {2} days",
period.Years, period.Months, period.Days);
重要的是要认识到结果代表了从现在起的时间"。或者,如果您替换不同的起点,那么(起点)"的时间。在任何情况下,您都不应该认为结果是X days = Y years + M months + D days
。这将是荒谬的,因为一年中的天数和一个月中的天数取决于 你正在谈论的年月。
答案 1 :(得分:0)
您只需要将天数添加到当前时间:
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;