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.
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
See SystemEvents class, UserPreferenceChang* events.
Related
My app works with a public calendar via CalDAV protocol (let's call it CalDAV calendar) which returns events in iCalendar format. One user started to create events in that calendar using Outlook localized to Russian language. It happened that Outlook put TZID field in the CalDAV calendar event in Russian language, as follows:
BEGIN:VCALENDAR
PRODID: some prod id
VERSION:2.0
BEGIN:VTIMEZONE
TZID:(UTC+03:00) Москва\, Санкт-Петербург
BEGIN:STANDARD
DTSTART:19710101T000000
TZOFFSETFROM:+0300
TZOFFSETTO:+0300
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
ORGANIZER;CN=UserName:MAILTO:username#mail.com
RRULE:FREQ=DAILY;UNTIL=20230108T100000Z
DTSTAMP:20230109T101100Z
UID:russiantz001
SEQUENCE:0
SUMMARY:Тест с 6 по 8 в 13 00 - 13 30
DTSTART;TZID="(UTC+03:00) Москва, Санкт-Петербург":20230106T130000
DTEND;TZID="(UTC+03:00) Москва, Санкт-Петербург":20230106T133000
DESCRIPTION:Russian TZ
CalDAV calendar treats events correctly. To deserialize iCalendar event I am using iCal.NET library which in turn uses NodaTime method DateTimeZoneProviders.Tzdb.GetZoneOrNull(TimeZoneId) to convert time from a time zone to UTC. It searches all time zone providers (IANA, BCL, serialization, etc) to see if TimeZoneId matches. Unfortunately, NodaTime does not understand TimeZoneId in Russian.
My question: how to get a correct English equivalent of the TimeZoneId in Russian generated by the localized Outlook?
.NET method FindSystemTimeZoneById throws exception that TimeZoneId is not found.
My app works in Linux environment. Therefore I cannot use Windows registry HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zones records. Moreover, to use registry records Windows should have been localized to the Russian language which would not happen for sure.
For now I am thinking just to use (UTC+03:00) prefix of the time zone Id in Russian, but I am not sure if this is right decision. For example, will time zone offset be correct during daylight saving period?
I would greatly appreciate any link or hint how to solve this conversion issue.
Time zone IDs should never be localized. What you have in the TZID field appears to be a time zone display name, not an ID. The application that created that file is incorrectly using the DisplayName property of the TimeZoneInfo object where it should be using Id property instead.
The correct Windows ID that should be showing in the file is "Russian Standard Time". Or it could (preferably) show the equivalent IANA time zone ID, which is "Europe/Moscow". They should be those exact strings and not translated to Russian.
The iCal format itself (and anything consuming it) doesn't care about this because it is strictly looking at the TZID field as it exists within the file. But anything else you use it for absolutely will.
The original application needs to be updated to return a time zone identifier instead of a display name in the TZID field.
Just using the time zone offset might be sufficient - but it may not always be. For example, if the time zone is one that changes offsets due to daylight saving time, the offset in the display name won't necessarily be the correct offset in effect for the event in the calendar.
The offset might also be different on the start time than on the end time, if the event crosses a DST transition. Moreover, if the event is recurring, the offset can be different between occurrences of events.
Then again, that particular time zone doesn't use DST (at least it doesn't presently), so you may never encounter such cases.
Well I am looking for a method to change the default windows 7 time format for a system.
So if a system uses like 10PM or 10 AM as default time notation, then i like to change that system to 10:00 or 22:00.
I know how to do it through the GUI, but in my case our software (C#) has to check if time notation is OK and if it is not change it by usage of
C#, registry editing, vbscript, commanline or Powershell, or some specific .exe file
The software we wrote allready makes usage of external progs / languages (vbscript/powershell).
But the problem is so far i have not found a method to do this other then taking over a remote screen.
Perhaps someone knows how to do this ?
The same counts for time zone, and date notation.
You may change the system time format using following code:
RegistryKey rk = Registry.CurrentUser.OpenSubKey(#"Control Panel\International", true);
rk.SetValue("sTimeFormat", "hh:mm:ss"); // HH for 24hrs, hh for 12 hrs
But IMO, this would not be a good practice for an application to change the system user's settings without the consent of the user.
I found this link that shows it being done via vb.net but you would have to translate it. or you could compile this to an exe and run it from a shell. http://www.access-programmers.co.uk/forums/showthread.php?t=152624
The property way to do this in .NET is with code such as the following:
CultureInfo newCultureInfo = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
newCultureInfo.DateTimeFormat.ShortDatePattern = shortDateFormat;
newCultureInfo.DateTimeFormat.LongTimePattern = longTimeFormat;
Thread.CurrentThread.CurrentCulture = newCultureInfo;
Regarding the solution using the "Control Panel\International" registry key (sorry, can't comment due to not have a 50 reputation):
This doesn't appear to affect the existing process, only new processes created after changing the registry. And obviously code assuming registry values (i.e. implementation details) could break in a future version of windows.
Also the code should Dispose the RegistryKey object. It would be better written with a using block.
Regarding if you should do this, while it would be unlikely an app would want to change the time date format (maybe an app that's an improved way of setting system info), it would be very reasonable to need to do this in an automated test. It's a common bug for code to depend on the default time/date format, so setting them to non-default values, or testing code with various time/date formats could be a good idea.
I am using DateTime.Now.ToString() to show the present time in an application. It appears fine in some computers, but in other computers, the time shows funny values.
For example, it shows 2010/11/09\0؎鶡撗䄠ϗ퉌؎鵢
Any ideas how to fix it?
its not funny .. go to control panel and change Regional and Language Options settings .. and try again
or use culture info
Please check the machine's date format. It should be of the same format which supports the application.
You can give it a format when converting:
DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");
I'm trying to make a system that basically allows me to shove a DLL in an installation and some code in an exe that allows me to release all of my future programs as beta releases for a while.
Now the problem is of course if I'd want to do that, i'd need to choose until when the program is valid. Which is fine, except that by changing your system clock, you can easily bypass the system.
Now, I'd like to hear what people generally do for something like this.
I've been trying a few approaches such as contacting a site to give the timestamp and compare that, which would be fine if it didn't always increase the program start time by over 9000
and and the fact that people would then not be able to use it if they're not connected to the internet.
Any suggestions are much appreciated.
This is not 100% guaranteed solution but it will take you there
You will need to implement these things in the config file (Why Config file, because if user deletes it your app won't run). Also encrypt all the following data.
Store the Date and Time on which application ran.
Store the exact amount of time for which application ran.
By doing so you can avoid:
If user change the computer time, you will come to know that, as your app is logging Date and Time, it might overlap the earlier time, say user ran app on 6th and 10th of month, and then he reverts date to 7th, you will come to know about it.
Secondly user can change the date on every run to single date, in that case the total duration used will help you. Say user set date to 1st of month every time he runs it, in that case, he can use app for 24 Hrs only not more than that.
Other options like
Checking time from External Server (Flaw: Requires internet access)
Storing Time in Registry (Flaw: User can easily manipulate registry)
Hope this helps you.
If your software can access some network share on some local server/nas, you can create a new file on this network share, and this file will have a creation time set using the clock of the server/nas, so you can compare the time set on the server/nas to the time of the local computer.
Or you can also save somewhere (a file, in the registry, in a DB) the last time of the last execution, and if the clock go back in time, then you can lock the application and require further assistance :-)
I use a VB6/COM+ application which outputs date/time values based on the short date settings in the Control Panel, Regional Settings, for the user that runs it. The program that then parses that output has a configurable setting for the date format it expects, and presents in the UI.
e.g. If the regional setting for the user is set to mm/dd/yyyy, and it outputs 06/18/2009, the application expecting "18/06/2009" fails with "String was not recognized as a valid DateTime".
As we usually run this application as a service account, which we have not logged in as interactively to create a profile, we generally set the correct date format and then tick the "Apply all settings to the current user account and the default user profile" option.
I would like to be make the C# configuration utility I have written for this mess to be able to set the date format programmatically for a given user.
Edit
I would like nothing more than to change the code, but do not have the ability to do so at this time.
I also know that what I am asking is a bad thing to do. With regards to "it should be the user's choice" - I am that user, as I create it explicitly for the task; I just want to set the date format by a scripted method, rather than having to do the clicking myself.
This is specifically discouraged by Microsoft. Any solution you may come up with will be a filthy hack that will probably stop working soon.
Think of it this way: who are you to decide those settings? Don't you think that's the user's decision?
Back on topic: find an unambiguous format for the applications to communicate in, such as YYYYMMDD. The application that displays can then simply respect the actual user settings, as it should.
But, since you can't change it, just poke into the registry:
Current user:
HKEY_CURRENT_USER\Control Panel\International
Specific user:
HKEY_USERS\(user SID)\Control Panel\International
Default user:
HKEY_USERS\.DEFAULT\Control Panel\International
sShortDate is probably the value you want to change.
If you are going to modify the profile to suit your needs, why not just ignore the profile settings and hardcode the format you want in your app?
code:
Imports System.Threading
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US", False)
Microsoft.Win32.Registry.SetValue("HKEY_CURRENT_USER\Control Panel\International", "sShortDate", "M/d/yyyy")
While persistently changing a user's culture (regional settings) is to be done cautiously, there are legitimate use cases.
On Windows 8 and Windows Server 2012 and above, Windows PowerShell comes with the
Set-Culture cmdlet, which is the programmatic equivalent of choosing a different region via Control Panel (intl.cpl).
For instance, Set-Culture fr-CA is the equivalent of interactively choosing region French (Canada) for the current user.
Caveat: Mixed cultures such as en-DE (sic) appear not to work as of Windows PowerShell v5.1 - see this answer of mine.
While it won't be fast, it is possible to call PowerShell commands from C#.