Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refesh short time string (C# DateTime.Now)?

I'm making a Notepad program with Windows Form and having a problem with the Date/Time feature:

My system time and date format (short) are hh:mm tt M/d/yyyy. When I press F5 (Date/Time feature) in Notepad, it add a time string with format like above. Then I change the system time and date format to HH:mm dd-MMM-YY and press F5 again in Notepad, it add another time string with the format I've changed.

But with my Notepad project (I use DateTime.Now.ToShortTimeString() and DateTime.Now.ToShortDateString() to do this feature), I have to start the program again if I want the format to take effect in my program, otherwise it will use the first format no matter how many times I press F5.

So I want to ask if there is a way to fix this.

I'm using VS 2013.

like image 920
Ryan Avatar asked Feb 10 '23 16:02

Ryan


1 Answers

Very good question. The date is formatted according to current user culture information, but the information is cached by .NET. What you need to do is force .NET to clear the cache by calling CultureInfo.ClearCachedData method beforehand.

More information here: https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.clearcacheddata(v=vs.80).aspx

Please also note, that clearing the cache every time a user wants to insert Date & Time is somehow missing the point of caching (OK, I am exaggerating a little bit). What you can do is only clear the cache, when the system tells you that its configuration has changed. You do this by listening to SystemEvents.UserPreferenceChanged event. More information in answer here: How to receive event when user changes system's culture

like image 178
Kuba Wyrostek Avatar answered Feb 24 '23 06:02

Kuba Wyrostek