MVC 获取日历开始日期和结束日期之间的天数
MVC Getting number of days between calendar start date and end date
我有 2 个日历,一个用于 select 开始日期的用户,另一个用于结束日期。我想获取两个日期之间的差值来显示天数。
decimal period = Convert.ToDecimal((currentApplication.StartDate.Value - currentApplication.EndDate.Value).TotalDays);
currentApplication.NoOfDays = period;
它确实有效,但天数不准确。
22/12 to 22/12 is displayed as 1.00
22/12 to 23/12 is displayed as -1.00
22/12 to 24/12 is displayed as -1.00
我认为使用 .TotalDays
是正确的,但值不准确。是我用错了还是 .TotalDays
不应该这样使用?
尝试一下;
decimal period = (currentApplication.startDate.Date - currentApplication.endDate.Date).TotalDays
如果使用 .TotalDays
时天数不准确,那么您可以使用 Timespan
来计算天数。
TimeSpan tSpan = (currentApplication.EndDate.Value).Subtract(currentApplication.StartDate.Value);
currentApplication.NoOfDays = tSpan.Days;
注意:请确保 currentApplication.StartDate.Value
和 currentApplication.EndDate.Value
是 DateTime。
我假设 startDate
和 endDate
是 Nullable<DateTime>
类型。
您应该先检查 HasValue
是否存在 Value。此代码应该适合您。
if(currentApplication.StartDate.HasValue && currentApplication.EndDate.HasValue)
{
currentApplication.NoOfDays = (currentApplication.EndDate.Value.Date - currentApplication.StartDate.Value.Date).Days;
}
我有 2 个日历,一个用于 select 开始日期的用户,另一个用于结束日期。我想获取两个日期之间的差值来显示天数。
decimal period = Convert.ToDecimal((currentApplication.StartDate.Value - currentApplication.EndDate.Value).TotalDays);
currentApplication.NoOfDays = period;
它确实有效,但天数不准确。
22/12 to 22/12 is displayed as 1.00
22/12 to 23/12 is displayed as -1.00
22/12 to 24/12 is displayed as -1.00
我认为使用 .TotalDays
是正确的,但值不准确。是我用错了还是 .TotalDays
不应该这样使用?
尝试一下;
decimal period = (currentApplication.startDate.Date - currentApplication.endDate.Date).TotalDays
如果使用 .TotalDays
时天数不准确,那么您可以使用 Timespan
来计算天数。
TimeSpan tSpan = (currentApplication.EndDate.Value).Subtract(currentApplication.StartDate.Value);
currentApplication.NoOfDays = tSpan.Days;
注意:请确保 currentApplication.StartDate.Value
和 currentApplication.EndDate.Value
是 DateTime。
我假设 startDate
和 endDate
是 Nullable<DateTime>
类型。
您应该先检查 HasValue
是否存在 Value。此代码应该适合您。
if(currentApplication.StartDate.HasValue && currentApplication.EndDate.HasValue)
{
currentApplication.NoOfDays = (currentApplication.EndDate.Value.Date - currentApplication.StartDate.Value.Date).Days;
}