Change System DateTime Format c#

陌路散爱 提交于 2019-12-04 05:20:00

问题


I need to change/update/set my system (windows7) default dateTime format programatically and permanently until I change it myself through code or through windows GUI

I have tried a lot of solutions like this one from Code Project

       Console.Write(DateTime.Now + "");
       RegistryKey rkey = Registry.CurrentUser.OpenSubKey(@"
       Control Panel\International", true);
        rkey.SetValue("sShortDate", "dd/MM/yyyy");
        rkey.SetValue("sLongDate", "dd/MM/yyyy");
       Console.Write(DateTime.Now + "");

The closest and well reputed answer is following from from Set Default DateTime Format c#, I tried this solution but it did not help me. As It does not change my system datetime format (shown in taskbar). And after I restart the app having this code, I again get the old format before this code is executed.

using System;
using System.Globalization;
using System.Threading;

namespace test 
{
    public static class Program
    {
        public static void Main() {
          Console.Write(DateTime.Now + "");// MessageBox.Show(DateTime.Now + "");
          CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
          culture.DateTimeFormat.ShortDatePattern = "dd-MMM-yyyy";
          culture.DateTimeFormat.LongTimePattern = "";
          Thread.CurrentThread.CurrentCulture = culture;
          Console.Write(DateTime.Now + "");// MessageBox.Show(DateTime.Now + "");
        }
    }
}

回答1:


I tried manually changing the registry keys mentioned in your question.

Here's what I did:

  • Pressed Win+R and type 'regedit' to get the Registry Editor.
  • Navigated the tree to Computer → HKEY_CURRENT_USER → Control Panel → International.
  • Double clicked the 'sShortDate' entry and changed the value to 'yyyy/MM/dd'.

I then opened Windows Explorer and all of the dates were shown in the new format, so this is definitely the right place in the registry.

I then tried the code you supplied to modify the registry and it, too, is changing the date shown in Explorer.

So, this leads me to believe that the Windows taskbar clock does not react to changes to this setting. I confirmed this by killing and restarting 'explorer.exe' from the Task Manager. If you restart Explorer you too should see the change take effect.


Edit: there appears to be no facility in .NET for setting the locale settings directly. You can, however, use P/Invoke to set it via the C++ Win API which should then cause the system clock (and other applications) to be notified of the change. See this discussion.



来源:https://stackoverflow.com/questions/12952089/change-system-datetime-format-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!