CSOM code gets executed from client machine and there’s a fair amount of chance that the current machine culture will not match with that of SharePoint Online site. Now, the problem is that for a ListItem of any List, SharePoint returns DateTime value in a string format. So, if you try to convert the string to a DateTime, you’ll get a FormatException that, the String was not recognized as a valid DateTime.
So, the solution is to get the current culture of the SharePoint Online site, and then apply the same to the current thread. To do that you need to query the LocaleId of the current site which, you can then use to get the CultureInfo.
//Getting and applying the SharePoint site culture to the working thread Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo(Convert.ToInt32(ctx.Web.RegionalSettings.LocaleId));
I have successfully tested this code for the following two conditions. My machine’s culture was en-US [MM/DD/YYYY] :-
- en-CA [DD/MM/YYYY]
- en-ZA [YYYY/MM/DD]
You can also see the List of CultureInfo.