## 2 replies

Last post May 31, 2019 02:31 AM by yogyogi

• slimbunny

Participant

855 Points

1467 Posts

### How do I get the number of months....

How do I get the number of months between two dates.
What is the c# formula for getting the months between dates.

Date set 1
date1 = 2/7/2016
date2 = 8/7/2016

Date set 2
Date3 = 12/3/2006
Date4 # 1/4/2008

Thank you
• Yuki Tao

Contributor

3570 Points

1425 Posts

### Re: How do I get the number of months....

May 31, 2019 02:11 AM|Yuki Tao|LINK

Hi slimbunny,

#### slimbunny

How do I get the number of months between two dates.
What is the c# formula for getting the months between dates.

I make a simply demo,you could refer to:

you could create a common function and call it

``` public static int GetMonthDiff(DateTime startDate, DateTime endDate)
{
int monthsApart = 12 * (startDate.Year - endDate.Year) + startDate.Month - endDate.Month;
return Math.Abs(monthsApart);
}```

hoe to call it:

```            DateTime now = DateTime.UtcNow;
int monthDiff = GetMonthDiff(now, past); //it return 12```

Best Regards.

Yuki Tao

MSDN Community Support
If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.
• yogyogi

Participant

990 Points

686 Posts

### Re: How do I get the number of months....

I suggest you to extract the month by using JavaScript reqular expression:

```date1 = 2/7/2016;
matches = /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})\$/.exec(date1);
var m1 = matches[1] - 1; // gives 7```
```date2 = 8/9/2016;
matches = /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})\$/.exec(date2);
var m2 = matches[1] - 1; // gives 9```

Also refer this date tutorial on JavaScript for more details.

Helping you always. Don't forget to click "Mark as Answer" on the post that helped you.
ASP.NET Core Tutorials → Start from the Beginning and become an Expert in 30 days time. ♠