Say I have 678 days, how to calculate how many years, months and days are there from that moment?
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);
You can indeed do this with Noda Time.
First, you need a starting point. This uses the current day in the local time zone. You may wish to use a different day, or a different time zone, depending on your scenario.
Instant now = SystemClock.Instance.Now;
DateTimeZone timeZone = DateTimeZoneProviders.Bcl.GetSystemDefault();
LocalDate today = now.InZone(timeZone).Date;
Then just add the number of days:
int days = 678;
LocalDate future = today.PlusDays(days);
Then you can obtain a period with the units desired:
Period period = Period.Between(today, future, PeriodUnits.YearMonthDay);
Console.WriteLine("{0} years, {1} months, {2} days",
period.Years, period.Months, period.Days);
It's important to recognize that the result represents "time from now". Or if you substitute a different starting point, it's "time from (the starting point)". Under no circumstances should you just think that the result is X days = Y years + M months + D days
. That would be nonsensical, since the number of days in a year and the number of days in a month depend on which year and month you're talking about.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With