Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodatime calculation of years/months/days in X days

Tags:

c#

nodatime

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);
like image 409
user3473957 Avatar asked Jan 10 '23 21:01

user3473957


1 Answers

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.

like image 64
Matt Johnson-Pint Avatar answered Jan 24 '23 06:01

Matt Johnson-Pint