Tuesday, September 8, 2009

Formatting CRM DateTime Field

As you might have noticed CRM DateTime field DataValue returns the following value: “Tue Sep 29 13:00:00 PDT 2009”
Sometimes you need to change the value to another format e.g. dd/mm/yyyy or mm-dd-yyyy hh:MM.
This is quite easy to do with C# since the format string is pretty extensive however the JavaScript Date object is pretty slim and so the only option is to write your own framework / prototype extension.

The following script extends the JavaScript Date Object and adds a toFormattedString function which accepts common format strings such as
dd – days, mm – months, yyyy – full year, hh – hours , MM – minutes , ss – seconds , ms – milliseconds , APM – AM/PM
You can extend the prototype function further if you require additional formatting.

Here is the code and usage example:

Date.prototype.toFormattedString = function(format)
var d = this;
var f = "";
f = f + format.replace( /dd|mm|yyyy|MM|hh|ss|ms|APM|\s|\/|\-|,|\./ig ,
function match()
case "dd":
var dd = d.getDate();
return (dd < 10)? "0" + dd : dd;
case "mm":
var mm = d.getMonth() + 1;
return (mm < 10)? "0" + mm : mm;
case "yyyy": return d.getFullYear();
case "hh":
var hh = d.getHours();
return (hh < 10)? "0" + hh : hh;
case "MM":
var MM = d.getMinutes();
return (MM < 10)? "0" + MM : MM;
case "ss":
var ss = d.getSeconds();
return (ss < 10)? "0" + ss : ss;
case "ms": return d.getMilliseconds();
case "APM":
var apm = d.getHours();
return (apm < 12)? "AM" : "PM";
default: return arguments[0];

return f;

function OnCrmPageLoad()
var d = new Date(crmForm.all..DataValue);
alert(d.toFormattedString("mm-dd-yyyy hh:MM:ss ms"));
alert(d.toFormattedString("dd/mm/yyyy hh:MM APM"));



Söderåsen said...

Hello, I am new in CRM world. I don't know if I can ask you this but I try. Is it possible to select many rows of an entity and then click a button like "Add this projectscontact" to another entity? For example I have "project" and I want to add more than one projeccontact at the same time...

Adi Katz said...

It's possible.

Simple solution:
Create a N:1 relationship between project contact and project and relate the contacts from the project entity form.

Advanced solution:
If you need this to be triggered from the project contact grid then you need to develop the solution by adding an isv.config button and a custom page that handles the relationship.

I also suggest posting your questions here Dynamics forums. This is a common requirement in many projects and I’m sure some will share their code bits with you.