Built something you're proud of? Tell the story. A quick G2 review of App Engine or Build Agent helps other developers see what's possible on ServiceNow. Share your experience.

Calculate months difference between two date fields

Elena Pomana
Tera Guru

Hello,

I have a task to calculate the number of months between two date fields.

(Price validity end date – Change date)

find_real_file.png

I tried to solve it with the code below, but I don't think that's the best approach.

var changeDate = new GlideDateTime(current.u_change_date).getNumericValue(); //get the value of change date field in milliseconds

var endDate = new GlideDateTime(current.u_price_validity_end_date).getNumericValue(); //get the value of change date field in milliseconds

var finalMilliseconds = endDate - changeDate; //result is in milliseconds
var finalSeconds = finalMilliseconds/1000; // transform in seconds;
var finalMonths = finalSeconds/2629800; //transform in months;
var finalDate = finalMonths.toFixed(2);

I have doubts that this is the correct answer, some months have 30 days, other 31 and February 28/29.

Will it work better with substract() method?! Any ideas?

 

Thank you,

Elena

1 ACCEPTED SOLUTION

Allen Andreas
Tera Patron

Hi,

If you get a moment, check out this thread for a similar requirement: https://community.servicenow.com/community?id=community_question&sys_id=e57f3ea9db58dbc01dcaf3231f96...

Please mark reply as Helpful/Correct, if applicable. Thanks!


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!

View solution in original post

2 REPLIES 2

Allen Andreas
Tera Patron

Hi,

If you get a moment, check out this thread for a similar requirement: https://community.servicenow.com/community?id=community_question&sys_id=e57f3ea9db58dbc01dcaf3231f96...

Please mark reply as Helpful/Correct, if applicable. Thanks!


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!

Hello,

 

Thank you for the thread! It helped! 🙂

 

Have a nice one,

Elena