I'm trying to use NodaTime to calculate the number of hours between two dates and I get this exception:
"Units contains time units: Hours. Parameter name: units"
This code works fine for years, months, and days.
public ElapsedTimeNodaTime(DateTime StartDate, DateTime EndDate)
{
var birthday = new LocalDate(StartDate.Year, StartDate.Month, Date.Day);
var today = new LocalDate(EndDate.Year, EndDate.Month, EndDate.Day);
Years = Period.Between(birthday, today, PeriodUnits.Years).Years;
Months = Period.Between(birthday, today, PeriodUnits.Months).Months;
Days = Period.Between(birthday, today, PeriodUnits.Days).Days;
Hours = Period.Between(birthday, today, PeriodUnits.Hours).Hours;
}
If you've just got dates, the simplest option is to multiply the number of days by 24.
Alternatively, create LocalDateTime
values instead:
Hours = Period.Between(birthday.AtMidnight(), today.AtMidnight(), PeriodUnits.Hours).Hours;
Or you could stick to LocalDateTime
for everything:
public ElapsedTimeNodaTime(DateTime startDate, DateTime endDate)
{
var birthday = startDate.ToLocalDateTime();
var today = endDate.ToLocalDateTime();
Years = Period.Between(birthday, today, PeriodUnits.Years).Years;
Months = Period.Between(birthday, today, PeriodUnits.Months).Months;
Days = Period.Between(birthday, today, PeriodUnits.Days).Days;
Hours = Period.Between(birthday, today, PeriodUnits.Hours).Hours;
}
It seems a little pointless though - why redundantly calculate hours when you've got days?
See more on this question at Stackoverflow