Defining a field as Date and Time allows an optimized data input, by presenting a floating calendar and capturing the user selection.
When creating a Date and Time field, you have a choice to specify whether to capture the date and time, or just the date.
For the purpose of this recipe, we will be building within the scope of the previously created solution. We will use the existing Birthday field on the Contact form, and target our scripts to this field. This field is defined as Date Only
.
We will be building a new function to read the value from this field first. Follow these steps:
JSDateTime
(new_JSDateTime
).function ReadBirthday() { var myContactBirthday; myContactBirthday = Xrm.Page.getAttribute("birthdate").getValue(); alert("Contact birthday is: " + myContactBirthday); }
OnChange
event of the Birthday field on the Contact form.One thing to note about the Date and Time fields in Dynamics CRM is that, even though we define a field as Date Only, the full date and time is stored, with a time defaulted to 0. If we want to retrieve only the date, we can either use the standard JavaScript functions to extract the year, month and day from the Date object as follows:
var year = myContactBirthday.getFullYear(); var month = myContactBirthday.getMonth(); // from 0 to 11 var day = myContactBirthday.getDate(); // from 1 to 31 month = month + 1; alert("Year: " + year + ", Month: " + month + ", Day: " + day);
On a new field defined as either Date Only or Date and Time, the following code will add the current date:
function SetBirthday() { var currentDateTime = new Date(); Xrm.Page.getAttribute("new_myDate").setValue(currentDateTime); }
Additionally, if a specific date value has to be added, it can be defined with standard JavaScript functionality in the variable that is being passed on to the setValue
function.
18.119.124.65