Jul 12, 2012

Reset Time of CrmDateTime

Surprisingly, I couldn’t find straightforward post of how to reset the time portion of the CrmDateTime. So I implemented my own method which worked for me. In fact, this might not the best code, but decent enough to use.

In my previous post I gave a hint that “Value” attribute is the key to CrmDateTime modifications/conversions. See, how I have used same attribute to modify the Time portion only.

public static CrmDateTime SetTime(CrmDateTime _dateTime,string _time)
{
  // considering datetime format as 2012-07-05T11:00:00+1000
  string _crmDTvalue = Convert.ToString(_dateTime.Value);
  string _crmDTvalueP1 = _crmDTvalue.Substring(0, 11);
  string _crmDTvalueP2 = _crmDTvalue.Substring(16);
  string _crmDTvalueNewTime = string.Concat(_crmDTvalueP1, _time, _crmDTvalueP2);

  CrmDateTime _crmDataTime = new CrmDateTime();
  _crmDataTime.Value = _crmDTvalueNewTime;

  return _crmDataTime;
}

Calling part;

//8 am
SetTime(_myCrmDateTime,"08:00");
//5 pm
SetTime(_myCrmDateTime,"17:00");

Please keep in mind, this method is subjective to the date time format you use, but this approach is easily used for any format.

No comments:

Post a Comment