How do i take a date field, add 5 years, then put answer in a new field?

Tony98
Mega Expert

I've got an Asset table with a Purchase Date field.

I need to add a new field called Lifecycle Expiration.

I then need to take the Purchase Date, add 5 years, then put that date in the Lifecycle field (read only field).

How do i do this?

find_real_file.png

1 ACCEPTED SOLUTION

Here's the code that I used. In my example, I subtracted a week, but the logic is the same and you can just tweak it to your own needs. Note that I'm adding 1 to the month because January returns as 0.



function onChange(control, oldValue, newValue, isLoading) {


    if (isLoading || newValue == '') {


          return;


    }



//Type appropriate comment here, and begin script below


var start_date = new Date(g_form.getValue('SOURCE VARIABLE'));


start_date.setDate(start_date.getDate() - 7);



var month = start_date.getMonth() + 1;


var day = start_date.getDate();


var year = start_date.getFullYear();


var work_start;



if(month < 10){


        month = "0" + month;


}


if(day < 10){


        day = "0" + day;


}



work_start = month + "-" + day + "-" + year;



g_form.setValue('DESTINATION VARIABLE', work_start);



}





Value('DESTINATION VARIABLE', work_start);


   


}


View solution in original post

8 REPLIES 8

Here's the code that I used. In my example, I subtracted a week, but the logic is the same and you can just tweak it to your own needs. Note that I'm adding 1 to the month because January returns as 0.



function onChange(control, oldValue, newValue, isLoading) {


    if (isLoading || newValue == '') {


          return;


    }



//Type appropriate comment here, and begin script below


var start_date = new Date(g_form.getValue('SOURCE VARIABLE'));


start_date.setDate(start_date.getDate() - 7);



var month = start_date.getMonth() + 1;


var day = start_date.getDate();


var year = start_date.getFullYear();


var work_start;



if(month < 10){


        month = "0" + month;


}


if(day < 10){


        day = "0" + day;


}



work_start = month + "-" + day + "-" + year;



g_form.setValue('DESTINATION VARIABLE', work_start);



}





Value('DESTINATION VARIABLE', work_start);


   


}


Jaspal Singh
Mega Patron
Mega Patron

Hi Anthony,



Setting the default value for the field as below would work.



javascript:var gdt = new GlideDateTime(gs.nowDateTime());gdt.addYears(5);gdt.getDate();


Hi Anthony,



If it worked you can mark this thread as correct & close it so that it does not appear in unanswered list.


sorry - still trying to get it to work