Question

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);
Was it helpful?

Solution 2

You just need to add the number of days to the current time:

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;

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top