在两个日期之间调用几个月C#

时间:2016-05-02 05:13:37

标签: c#

我试图在GetMonths()方法中调用Row_Inserting()方法,但它显示错误。另外,如何将此方法的值复制到名为Total_Pay的变量?

public override bool Row_Inserting(OrderedDictionary rsold, ref OrderedDictionary rsnew) 
{      
    GetMonths(FROM_DATE, TO_DATE);
    return true;
}

public int GetMonths(DateTime FROM_DATE, DateTime TO_DATE)
{
    if (FROM_DATE > TO_DATE)
    {
        throw new Exception("Start Date is greater than the End Date");
    }

    int months = ((TO_DATE.Year * 12) + TO_DATE.Month) - ((FROM_DATE.Year * 12) + FROM_DATE.Month);

    if (TO_DATE.Day >= FROM_DATE.Day)
    {
        months++;
    }

    return months;
}

1 个答案:

答案 0 :(得分:0)

希望这会有所帮助..

    public override bool Row_Inserting(OrderedDictionary rsold, ref OrderedDictionary rsnew)
    {
        int Total_Pay;
        DateTime FROM_DATE = DateTime.Parse("02-May-2016"); //Replace with date you need
        DateTime TO_DATE = DateTime.Parse("08-May-2016"); //Replace with date you need
        Total_Pay = GetMonths(FROM_DATE, TO_DATE);
        return true;
    }

    public int GetMonths(DateTime FROM_DATE, DateTime TO_DATE)
    {
        if (FROM_DATE > TO_DATE)
        {
            throw new Exception("Start Date is greater than the End Date");
        }
        int months = ((TO_DATE.Year * 12) + TO_DATE.Month) - ((FROM_DATE.Year * 12) + FROM_DATE.Month);
        if (TO_DATE.Day >= FROM_DATE.Day)
        {
            months++;
        }
        return months;
    }

并查看此类似问题Link