我试图使用NodaTime来计算两个日期之间的小时数,我得到了这个例外:
"单位包含时间单位:小时。参数名称:units"
此代码可以正常使用数年,数月和数天。
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;
}
答案 0 :(得分:16)
如果您有日期,最简单的选择是将天数乘以24。
或者,改为创建LocalDateTime
值:
Hours = Period.Between(birthday.AtMidnight(), today.AtMidnight(), PeriodUnits.Hours).Hours;
或者你可以坚持LocalDateTime
所有事情:
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;
}
虽然看起来有点无意义 - 为什么要多余地计算你有几天的时间?