please dont ask me why, but I need to write a simple programm that prints out the current System Date and Time in the format, the system is configured in.
Example: System Date is 03.03.2018 , click button and print out date in dd.mm.yyyy format Change the System Region/Clock to 03/03/2018, click button and print out in dd/mm/yyyy format. What I tried was to write a Method, using the DateTime class and assign DateTime.Now to a DateTime var. Then use the propertie "ToLocalTime()" to get the correct format. This method gets called, as soon as I hit a refresh button.
private String getSystemDate(){
DateTime date = DateTime.Now;
date = date.ToLocalTime();
return date.ToString(); ;
}
The problem is, that the label I assign the return value of getSystemDate() doesnt contain the correct formating. Only after restarting the application, the date is displayed in the new format.
Any suggestions?
You need to clear the locale cache. When your application starts up, it caches the current Windows locale. It doesn't refresh it on its own.
https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.clearcacheddata.aspx
(emphasis mine)
Information, such as the default culture and format patterns, is cached the first time it is requested. That information can change during the life of the AppDomain, for example, when the user modifies the regional and language options portion of Control Panel. However, the
CultureInfo
class does not automatically detect changes in the system settings.The
ClearCachedData
method clears the cache ofCultureInfo
objects created byGetCultureInfo
and refreshes the information in theCurrentCulture
,CurrentUICulture
, andCurrentRegion
properties, based on the current system settings.The ClearCachedData method does not refresh the information in the
Thread.CurrentCulture
property for existing threads. However, future threads will have any newCultureInfo
property values.