Sep 13, 2011

DateFormats and Ascentium CrmService

Playing around with DateTimes seems quite hectic to me. Specially, when you work in client side with Ascentium CrmService, it becomes tricky since you need to do your operations in usual DateTime format available in JavaScript and convert them from/to methods in the service.

For example, if you need some DateTime operation done in your logic using JavaScript, for some value comes from a Fetch result, first you need to convert them to a DateTime field. Fetch returns strings. There is no simple way for that but to do it with some string operations as below.

//convert DATE String (2008-01-01T00:00:00) format 
//to DATE (Tue Aug 23 07:00:00 UTC+1000 2011)
DateFormatFromAttributeValue = function(DateStr)
    var yearStr, YearStr, DayStr, MonthStr, HourStr, MinStr, NewDateStr;
    yearStr = DateStr.substr(0, 4);
    MonthStr = String(DateStr.substr(5, 2) - 1); //Month goes as 0-11
    DayStr = DateStr.substr(8, 2);
    HourStr = DateStr.substr(11, 2);
    MinStr = DateStr.substr(14, 2);

    return new Date(yearStr, MonthStr, DayStr, HourStr, MinStr, 0);

It is interesting to see that you get three string values from the Fetch as below.

My advice is to use “value” field for all your operations even if you need just the date. I am telling this because, date string is not consistent with the length which could drag you to a mess when handling. If you see carefully, in above example, date is shown as “2” not “02”. In fact, number of characters in the string could be different when date is less than 10th day and greater than 10th Day. This should be a big concern when string functions are being used for conversions.

When you need to submit a DateTime, you got to convert it back to the previous string format (i.e. 2008-01-01T00:00:00). I use below method for that.

//convert DATE (Tue Aug 23 07:00:00 UTC+1000 2011) 
//to DATE String (2008-01-01T00:00:00) format
DateFormatPassToService = function(DateValue)
  var YearStr, DayStr, MonthStr, HourStr, MinStr, NewDateStr;
  YearStr = DateValue.getFullYear();
  MonthStr = String(parseInt(DateValue.getMonth()) + 1); //Month goes as 0-11
      if (MonthStr.length == 1) { MonthStr = '0' + MonthStr; }
  DayStr = String(DateValue.getDate());
      if (DayStr.length == 1) { DayStr = '0' + DayStr; }
  HourStr = String(DateValue.getHours());
      if (HourStr.length == 1) { HourStr = '0' + HourStr; }
  MinStr = String(DateValue.getMinutes());
      if (MinStr.length == 1) { MinStr = '0' + MinStr; }
  return (YearStr + '-' + MonthStr + '-' + DayStr + 'T' + HourStr + ':' + MinStr + ':00');

Hope this will help you.

No comments:

Post a Comment