Useful Date Functions

1 minute read time.

Occasionally you will need to fetch a date from either the CRM database or perhaps from an external system that is then needs to be formatted so it looks like a CRM date.

All users are able to set their date preferences.

The are other articles that discuss handling dates

The functions show below can be used to format a date and cause it to be displayed according to the user preferences. The example is based on usage in an ASP page but the code could be modified for other pruposes.

With out the usage of the function the retrieved dates would look like:

With the function the dates look correct


Functions

/////////////////////////////////////////////////////////////////////////
//
//         Leading zeros
//
//////////////////////////////////////////////////////////////////////////

function leadingZero(x)
{
//this examines a number to determine whether or not to add leading zeros.
//useful for dates
//example usage:
//var myDate = new Date();
//Response.Write(leadingZero(myDate.getDate()));
//
if (x <10)
return '0'+x;
else
return x;
}

////////////////////////////////////////////////////////////////////////
//
//          Formatting of Dates
//
//////////////////////////////////////////////////////////////////////////

function formatDate(x)
{
// This retrieves the users preferred dates and uses this to format returned dates.
//makes use of the leadingZero function

var myRecordId = eWare.GetContextInfo('user','user_userid');
var myRecord = eWare.FindRecord('usersettings',"uset_key like 'NSet_userdateformat%' and uset_userid="+myRecordId);
var sourceDate = new Date(x);

var gotDate = leadingZero(sourceDate.getDate())
var gotMonth = leadingZero(sourceDate.getMonth()+1);
var gotYear = sourceDate.getYear();
var gotHours = leadingZero(sourceDate.getHours());
var gotMinutes = leadingZero(sourceDate.getMinutes());
var gotTime = gotHours+':'+ gotMinutes;
var resultDate

switch(myRecord.uset_value)
{
case 'mm/dd/yyyy':
resultDate = gotMonth +'/'+ gotDate +'/' + gotYear +' '+gotTime;
//+ ' ' + sourceDate.getHours() +':' sourceDate.getMinutes()
return resultDate;

case 'dd/mm/yyyy':
resultDate = gotDate +'/' + gotMonth+'/'+ gotYear +' '+gotTime;
//+ ' ' + sourceDate.getHours() +':' sourceDate.getMinutes()
return resultDate;

case 'yyyy/mm/dd':
resultDate = gotYear +'/' + gotMonth +'/'+ gotDate +' '+gotTime  ;
//+ ' ' + sourceDate.getHours() +':' sourceDate.getMinutes()
return resultDate;

default:
resultDate = gotMonth +'/'+ gotDate +'/' + gotYear +' '+gotTime;
//+ ' ' + sourceDate.getHours() +':' sourceDate.getMinutes()
return resultDate;
}
}

Downloadable example

The functions have been used in an example rebuild of the Company Quicklook Page. Development Partners can download the code from here.

Parents Comment Children
No Data