I am working on a Item Update event receiver in a SharePoint document library. One of the fields in this library is a Date and Time (Date only format) field. When a user selects a date and clicks on the OK/save button, the ItemUpdating
event receiver method must validate the date value by checking if the selected date is less than or equal to the current day's date. If the selected value is a future date, an error message is displayed, prompting the user to revise the date.
The code to extract before and after values on that field is:
// pre-updating
value = eventProperties.ListItem[eventProperties.ListItem.Fields[fieldName].InternalName];
// post-updating
value = eventProperties.AfterProperties[fieldName];
I selected a date of April 14, 2016 in the calendar control on the Edit Form page. Since it is a future date (today's date is March 12, 2016), I displayed an error message to alert the user of the constraint violation and also displaying the entered date and the current day's date. But the error message is displaying 04/13/2016 instead of 04/14/2016.
Regardless of how SharePoint stores the input value in the database, how do I get the value exactly as entered in the form so I can display that same value in any error message?
Answer summary
// Code to retrieve pre-updating value
value = eventProperties.ListItem[eventProperties.ListItem.Fields[fieldName].InternalName];
DateTime.Parse(value.ToString()).ToUniversalTime().ToShortDateString();
// Code to retrieve post-updating value
value = eventProperties.AfterProperties[fieldName];
DateTime dtValue = DateTime.Parse(value.ToString());
SPWeb web = properties.OpenWeb();
SPTimeZone timeZone = web.RegionalSettings.TimeZone;
timeZone.LocalTimeToUTC(dtValue).ToShortDateString();