Adding and setting date field on client side

jamesmcwhinney
Giga Guru

From the client side, I am trying to autopopulate an end date field after the start date field has been entered.

Here is my current code:

Catalog Client Script - OnChange - StartDate

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

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

          return;

    }

  var str_start = g_form.getValue('start_datetime');

  var dt_start = new Date(str_start);

  var addDays = 30;

  var dt_end = new Date(str_start);

  dt_end.setDate(dt_end.getDate() + addDays);

  var month = "" + (dt_end.getMonth() + 1); //Not sure why I need to add 1 but I do for some reason. is January month zero??

  if(month.length < 2){

        month = '0' + month;

  }

  var day = "" + dt_end.getDate();

  if(day.length < 2){

      day = '0' + day;

  }

  var year = dt_end.getFullYear();

  g_form.setValue('end_datetime', year + "-" + month + "-" + day);

}

This works fine when the current user's ServiceNow profile is set to yyyy-mm-dd, but not if it is any other date format.

Could anyone offer any suggestions?

Thanks!

- James

6 REPLIES 6

jamesmcwhinney
Giga Guru

Looks like there is no good way to resolve this without ajax calls to the server side =(



I am going to implement the workaround shown here:


Client Script Date/Time Functions


Nope that didnt account for the user profile date format variations either,..


Yes, if you use java script functions in client side, it may cause some errors, when profile format date changes.


use this Client Script Date/Time Functions logic only.



For your scenario addDateTimeAmount this function will suit.



even if you can get this client side also, but again you need to convert the date into user profile date format, like by calling g_user_date_time_format first, bsed on this you need to convert in client side, it takes so much validations. So try with Glideajax call only.


Thanks!!


g_user_date_time_format is what I was missing!



Here is my revised script:



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


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


          return;


    }


    //Get The start date


  var str_startDate = g_form.getValue('start_datetime');


      //Add 30 Days


  var dt_end = new Date(str_startDate);


  dt_end.setDate(dt_end.getDate() + 30);


    //Get end date string with user preference format in mind


  var str_endDate = formatDate(dt_end, g_user_date_time_format);


  //Remove time stamp


  var arr_endDate = str_endDate.split(' ');


  g_form.setValue('end_datetime', arr_endDate[0]);


}