find and solve || findandsolve.com
Please wait.....

Welcome back.






Before Read Terms of use

Count months Between Start and End Date C#

Count months Between Start and End Date C#

How to calculate total month from FromDate and ToDate in c#?. I don't want to divide this number by 30 because of every month is not 30 days or some grater then 30 and since the two operand values are quite apart from each other.


Answers

Option 1.

Create Function like as 

 public static int TotalMonthCount(int endMonthId, int startMonthId)
        {
            int totalMonth = endMonthId - startMonthId;
            if (totalMonth == 0)
            {
                return totalMonth = 1;
            }
            else if (totalMonth == -11)
            {
                return 1;
            }
            else if (totalMonth == -10)
            {
                return 3;
            }
            else if (totalMonth == -9)
            {
                return 4;
            }
            else if (totalMonth == -8)
            {
                return 5;
            }
            else if (totalMonth == -7)
            {
                return 6;
            }             else if (totalMonth == -6)
            {
                return 7;
            }
            else if (totalMonth == -5)
            {
                return 8;
            }
            else if (totalMonth == -4)
            {
                return 9;
            }             else if (totalMonth == -3)
            {
                return 10;
            }
            else if (totalMonth == -2)
            {
                return 11;
            }
            else if (totalMonth == -1)
            {
                return 12;
            }
            return totalMonth;
        }

and call this function like as

int totalMonth =TotalMonthCount(ToDate.Month,FromDate.Month);

Option 2.

Assuming that day of the month is irrelevant (i.e. the diffent between 2021.1.1 and 2020.12.31 is 1), withToDate >(is grater then) FromDate giving a positive value and FromDate >ToDate a negative value.

((ToDate.Year - FromDate.Year) * 12) + ToDate.Month - FromDate.Month;

or

ToDate.Subtract(fromDate).Days / (365.25 / 12);

Option 3.

public static int GetTotalMonth(DateTime startDate, DateTime endDate)
{
    int totalMonth= 12 * (startDate.Year - endDate.Year) + startDate.Month - endDate.Month;
    return Math.Abs(totalMonth);
}
DateTime now = DateTime.UtcNow;
DateTime past = now.AddMonths(-13);
int monthDiff = GetTotalMonth(now, past);

Mahira  khanna

Mahira khanna

I have the skills you need for you company blog, website, or other content materials

Comments



Report Response