如果我以今天的日期开始并计数为5天,则会显示4天。如果我将开始日期后移1,则显示6这是我当前拥有和可以使用的内容,除非我使用今天的日期作为开始日期。
private void DaysToShow()
{
//Find the difference in the days selected in the drop down menu so we can calculate
DateTime dtDateOnQuay = dtpDateOnQuay.Value;
DateTime dtDateLeft = dtpDateLeft.Value;
TimeSpan difference = dtDateLeft - dtDateOnQuay;
//As the days are inclusive and the above gets the days in between, add 1
m_iDaysRent = difference.Days + 1;
m_iDaysDetention = m_iDaysRent;
if (dtpDateReturned.Checked)
{
TimeSpan oDetentionDiff = dtpDateReturned.Value - dtpDateOnQuay.Value;
m_iDaysDetention = oDetentionDiff.Days + 1;
}
txtDaysOnQuay.Text = m_iDaysRent.ToString();
txtDaysDetention.Text = m_iDaysDetention.ToString();
}
我认为您的问题可能是日期的时间角度。您不需要它,因此您可能应该尝试以下解决方案。
检查忽略时间的DaysToShowByDateComp。
public class Program
{
public static void Main()
{
DateTime endDate = DateTime.Parse("2019-10-01 23:59:59");
DateTime startDate2 = DateTime.Parse("2019-10-04 00:00:00");
DateTime endDate2 = DateTime.Parse("2019-10-01 00:00:00");
Console.WriteLine(DateTime.Now.ToString());
Console.WriteLine(endDate.ToString());
Console.WriteLine("With today timespan:" + DaysToShowByTimeComp(DateTime.Now, endDate));
Console.WriteLine("With today date comparison:" + DaysToShowByDateComp(DateTime.Now, endDate));
Console.WriteLine("With other timespan:" + DaysToShowByTimeComp(startDate2, endDate2));
Console.WriteLine("With other date comparison:" + DaysToShowByDateComp(startDate2, endDate2));
}
private static int DaysToShowByTimeComp(DateTime start, DateTime end)
{
//Find the difference in the days selected in the drop down menu so we can calculate
DateTime dtDateOnQuay = end;
DateTime dtDateLeft = start;
TimeSpan difference = dtDateLeft - dtDateOnQuay;
//As the days are inclusive and the above gets the days in between, add 1
return difference.Days + 1;
}
private static int DaysToShowByDateComp(DateTime start, DateTime end)
{
return (int)((start.Date - end.Date).TotalDays) + 1;
}
}
输出为
10/4/2019 2:18:23 PM
10/1/2019 11:59:59 PM
With today timespan: 3
With today date comparison: 4
With other timespan: 4
With other date comparison: 4
更改了数学运算符并转换为如下所示的int并可以正常使用
private void DaysToShow()
{
//Find the difference in the days selected in the drop down menu so we can calculate
DateTime dtDateOnQuay = dtpDateOnQuay.Value;
DateTime dtDateLeft = dtpDateLeft.Value;
TimeSpan difference = dtDateLeft.Subtract(dtDateOnQuay);
//As the days are inclusive and the above gets the days in between, add 1
m_iDaysRent = Convert.ToInt32(difference.TotalDays) +1;
m_iDaysDetention = m_iDaysRent;
if (dtpDateReturned.Checked)
{
TimeSpan oDetentionDiff = dtpDateReturned.Value - dtpDateOnQuay.Value;
m_iDaysDetention = oDetentionDiff.Days + 1;
}
txtDaysOnQuay.Text = m_iDaysRent.ToString();
txtDaysDetention.Text = m_iDaysDetention.ToString();
}