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.