Javascript Date Library for CRM Page scripting

This is a quick help for all those Dynamics CRM 2011 souls out there dealing with page validation routines that invlove Dates. Javascript date manipulation is not for the faint of heart. This article does deal with date validation as in checking with date diffs, comparing dates and formating dates to be displayed as messages and also for setting dates in the correct formats whehn dealing with language and culture information other than english.

Date Comparision:

I started with a simple requirements. Check to see if one date is earlier than another date. First of allI cannot do this in Javascript.

var date1 = new Date(Xrm.Page.getAttribute(“firstDate”).getValue();

var date2 = new Date(Xrm.Page.getAttribute(“secondDate”).getValue();

In cannot do this in CRM event script

if (date < date2)   // this script will not run and will exit executinn of the function.

you have to take the diff and see if it is less than zero(0)

if ( (date – date2) < 0)  // this will actually fetch the difference in millisenconds and will be accurate.

Javascript Date Libraries:

First choice was to use Google DateJS library. As usual very drveloper friendly. I used Date JS, EN culture for formating date for error messages. One big issue I ran into with the library was that getAttribute would not fetch the date entered value on the form, would only fetch the date when form loaded. This was very annoying and had to dump DateJS. (http://code.google.com/p/datejs/ )

Second Choice, looked up Jacob Wright’s implementation of formating javascript dates and this would not work in the correct way either. Did not display the month correctly when using “m” as defined in the blog. This library did not interfere with Xrm.Page Data Entity methods. (http://jacwright.com/projects/javascript/date_format/ )

Third Choice was “F Is For Format” javascript library. Finally I got the javascript date formating to work correctly. Please check out this library at (http://fisforformat.sourceforge.net/ )

Enjoy and let me know if you see the behaviors of these libraries within CRM event model work any better or worse.

NOTE: I did not check out JQuery or JQuery UI to find a solution for date formatting, since I got my solution from “F is for Format”.

Prabhakar.

Advertisements