4

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.

Ryan
  • 135
  • 9
  • I don't understand. Why don't you insert (I don't know where you insert either) them as a DateTime, not a string? Where did you insert them exactly? How about generating a specific format with custom specifiers instead of using `ToShortDateString` and/or `ToShortTimeString`? – Soner Gönül Jul 04 '15 at 11:44
  • Yeah, It's true that I can just use my own format but I want my program exactly like Notepad :D – Ryan Jul 04 '15 at 12:08

2 Answers2

7

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

Community
  • 1
  • 1
Kuba Wyrostek
  • 6,163
  • 1
  • 22
  • 40
1

See SystemEvents class, UserPreferenceChang* events.

Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49