首页 > 解决方案 > 在 C# 中,我试图显示 2 个日期时间选择器之间的天数,包括选择的天数,但如果我选择今天的日期,它不会添加 1 天

问题描述

如果我从今天开始计算 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();
}

标签: c#datetimetimespanpicker

解决方案


更改了数学运算符并转换为 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();
    }

推荐阅读