How to modify a DateTime value of AfterProperties in ItemUpdating/ ItemAdding Events in SharePoint
Issue Description:
- 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
- Error "Invalid date/time value. A date/time field contains invalid data. Please check the value and try again."
Steps to REPRO the Issue:
- Created a SharePoint Customer List
- Add a new custom Column of type DateTime (Example: ApprovedTimeStamp)
- Created a Feature Receiver Event Handler Assembly implementing ItemUpdating/ ItemAdding event.
(Note: EventHandler sample showing ItemUpdating code is attached in the blog) - 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. "
- 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:
- properties.AfterProperties["ApprovedTimeStamp"] = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"); // Works Fine
- properties.AfterProperties["ApprovedTimeStamp"] = Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now); // Works Fine
Comments
- Anonymous
August 06, 2009
(Y) Thanks! SPUtility.CreateISO8601DateTimeFromSystemDateTime works great!