Setting value in DateTime field in PowerApps/ Dynamics 365 Portals dynamically using Javascript

You may be wondering why this simple post? After all, setting a date value, what’s in that?

Sometimes the simplest of things takes us by surprise. Below is a screenshot of an entity form with date field.

image

Based on custom business logic on the client side, we have to set the value of the date field (cr6b0_datefield).

If you are thinking just setting the value of the datefield with this line –>  $(“#crb60_datefield”).val(new Date()) will work, it unfortunately won’t.

Below is sample function I have written to set the value of the date field.

function setDateControlFieldValue(fieldname)

{

var d=new Date();

//take the date field

var datefield = $(‘#’+ fieldname);

//take the input control for the date picker

var inputControl = $(‘#’+ fieldname +’_datepicker_description’);

//take the date format

var dateFormat = inputControl.attr(‘data-date-format’);

//set the value to control

datefield.val(moment.utc(d).format(‘YYYY-MM-DDTHH:mm:ss.0000000\\Z’));

//set the value to input control

inputControl.val(moment(d).format(dateFormat));

}

The first thing you should remember is datepicker control in bootstrap uses moment.js to set up the date value. If you just specify the date value, platform won’t detect it.

Let me explain why we need to set value input control description field. If we simply try to set the value of date field the value gets set but the date picker description is not set like

$(“#” +fieldname).val(new Date());

clip_image002

In order to set the description value we need to get hold of that control as well.

clip_image004

Setting the value to input control description will reflect the date in UI.

I have used date only field here, even for DateTime field as well the input control description format would be similar to date field as:

“<field_schemaname>”_datepicker_description

Have you ever thought a functionality as small as this can take you for a ride.

Hope this helps!

Debajit Dutta

(Business Solutions MVP)

For training and consulting, please visit info@xrmforyou.com