Monday, December 20, 2010

DateTime to CrmDateTime conversion

We all know that DateTime in C# is different than CrmDateTime.
In CrmDateTime we also have two things 1. UserTime and 2. UniversalTime.
To convert from normal DateTime to CrmDateTime follow the follwoing code.

public static CrmDateTime ConvertToCRMDateTime(DateTime dateTime)
{
CrmDateTime crmDateTime = new CrmDateTime();
crmDateTime.date = dateTime.ToShortDateString(); //assign the date
crmDateTime.time = dateTime.ToShortTimeString();//assign the time
//now create the offset from the timezone
TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
string sOffset = string.Empty;
if (offset.Hours < 0)
{
sOffset = "-" + (offset.Hours * -1).ToString().PadLeft(2, '0') + ":";
}
else
{
sOffset = "+" + offset.Hours.ToString().PadLeft(2, '0') + ":";//":" is more inmportant
}
sOffset += offset.Minutes.ToString().PadLeft(2, '0');
crmDateTime.Value = dateTime.ToString(string.Format("yyyy/MM/ddTHH:mm:ss{0}", sOffset));
return crmDateTime; //finally return the CrmDateTime format
}

No comments:

Post a Comment