How to calculate total months between a Start date and End date?

Community Alums
Not applicable

Hi,

I am trying to calculate the Current Financial Years total months present between Start Date and End Date.

Case 1:

Start Date = 01/01/2022

End Date = 12/31/2024

Current FY months = 12 (i.e. Current year is 2023 so 12 months in 2023)

 

Case 2:

Start Date = 01/01/2022

End Date = 31/05/2023

Current FY months = 5 (i.e. Current year is 2023 only upto 5th month so its 5 months in 2023)

How do I calculate this using scripting?

 

Thanks in advance!!!!

1 ACCEPTED SOLUTION

Basheer
Mega Sage

Hi @Community Alums ,

Here you go

var months = 12;
var monthDiff= 0;

var startDate= new GlideDate();
startDate.setValue(current.start_date);
var gdtStart= new GlideDateTime(startDate);
var monthsStart=gdtStart.getMonthLocalTime();
var yearStart=gdtStart.getYearLocalTime();

var endDate= new GlideDate();
endDate.setValue(current.end_date);
var gdtEnd= new GlideDateTime(endDate);
var monthsEnd=gdtEnd.getMonthLocalTime();
var yearEnd=gdtEnd.getYearLocalTime();

if(yearStart != yearEnd){
monthDiff=(12-monthsStart)+(monthsEnd-1)+(yearEnd-yearStart-1)*12;
}
else{
monthDiff=monthsEnd-monthsStart-1;
}

//monthDiff gives us the month difference
Please hit like button if my suggestion has helped you in any way.
Please mark correct if my response has solved your query.

Cheers,
Mohammed Basheer Ahmed.

View solution in original post

3 REPLIES 3

Basheer
Mega Sage

Hi @Community Alums ,

Here you go

var months = 12;
var monthDiff= 0;

var startDate= new GlideDate();
startDate.setValue(current.start_date);
var gdtStart= new GlideDateTime(startDate);
var monthsStart=gdtStart.getMonthLocalTime();
var yearStart=gdtStart.getYearLocalTime();

var endDate= new GlideDate();
endDate.setValue(current.end_date);
var gdtEnd= new GlideDateTime(endDate);
var monthsEnd=gdtEnd.getMonthLocalTime();
var yearEnd=gdtEnd.getYearLocalTime();

if(yearStart != yearEnd){
monthDiff=(12-monthsStart)+(monthsEnd-1)+(yearEnd-yearStart-1)*12;
}
else{
monthDiff=monthsEnd-monthsStart-1;
}

//monthDiff gives us the month difference
Please hit like button if my suggestion has helped you in any way.
Please mark correct if my response has solved your query.

Cheers,
Mohammed Basheer Ahmed.

Community Alums
Not applicable

But @Basheer this solution doesn't calculate the months in the current Year. It is supposed to return the no of months which is against the current Financial Year.

Community Alums
Not applicable

Thanks @Basheer