Working with date and time

Defining a field as Date and Time allows an optimized data input, by presenting a floating calendar and capturing the user selection.

Working with date and time

When creating a Date and Time field, you have a choice to specify whether to capture the date and time, or just the date.

Getting ready

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.

How to do it...

We will be building a new function to read the value from this field first. Follow these steps:

  1. Add a new JScript web resource, named JSDateTime (new_JSDateTime).
  2. Insert the following function which reads the current field value and pops up an alert with the value:
    function ReadBirthday()
    {
          var myContactBirthday;
          myContactBirthday = Xrm.Page.getAttribute("birthdate").getValue();
          alert("Contact birthday is: " + myContactBirthday);
    }
  3. Associate this function with the OnChange event of the Birthday field on the Contact form.
  4. Save and Publish.
  5. Open a contact and change the Birthday field value. A popup will come up looking as follows:
    How to do it...

How it works...

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);  

There's more...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.124.65