How to modify a DateTime value of AfterProperties in ItemUpdating/ ItemAdding Events in SharePoint

Issue Description:

  1. When you change the value of the DateTime column of Custom List in SharePoint's SPItemReceiver AfterProperties/BeforeProperties you need to set it to a specific DateTimeFormat string or else it throws the Error
  2. Error "Invalid date/time value. A date/time field contains invalid data. Please check the value and try again."

Steps to REPRO the Issue:

  1. Created a SharePoint Customer List
  2. Add a new custom Column of type DateTime (Example: ApprovedTimeStamp)
  3. Created a Feature Receiver Event Handler Assembly implementing ItemUpdating/ ItemAdding event.
    (Note: EventHandler sample showing ItemUpdating code is attached in the blog)
  4. Try to assign value to the Datetime Column of After Properties in ItemUpdating/ ItemAdding event. If you assign value either of the below mentioned way it throws Error: "Invalid date/time value. A date/time field contains invalid data. Please check the value and try again. "
  5. properties.AfterProperties["ApprovedTimeStamp"] = DateTime.Now ;    //Generates Error
    properties.AfterProperties["ApprovedTimeStamp"] = DateTime.Now.ToString();    //Generates Error
    properties.AfterProperties["ApprovedTimeStamp"] = new DateTime(2008, 11, 08) ;    //Generates Error
    properties.AfterProperties["ApprovedTimeStamp"] = DateTime.Now.ToLongDateString();    //Generates Error
    properties.AfterProperties["ApprovedTimeStamp"] = DateTime.Now.ToShortDateString();    //Generates Error

Resolution / WorkAround:
When setting a DateTime value in AfterProperties you have to convert the the DateTime to an ISO8601 string format. Either of the below mentioned line can be used to assign value to DateTime Column of Afterproperties in ItemUpdating/ ItemAdding Event:

  1. properties.AfterProperties["ApprovedTimeStamp"] = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"); // Works Fine
  2. properties.AfterProperties["ApprovedTimeStamp"] = Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now); // Works Fine