C#更改系统日期时间格式

时间:2015-07-07 11:38:14

标签: c#

我正在寻找一种方法将系统的日期时间格式从12小时更改为24小时。假设,目前,我有12或24小时格式的系统时间,我想以编程方式将其更改为24小时格式。怎么可能?

由于

1 个答案:

答案 0 :(得分:1)

您可以使用SetLocaleInfo API函数,并将LOCALE_ITIME常量作为LCType参数传递。

修改

以下是设置12小时时间格式的示例。

using System;
using System.Runtime.InteropServices;

namespace DllImportTest
{
    internal static class Program
    {
        private const string TimeFormat12Hour = "0";
        private const string TimeFormat24Hour = "1";

        public static void Main(string[] args)
        {
            var ok = WindowsApi.SetLocaleInfo(0, WindowsApi.LOCALE_ITIME, TimeFormat12Hour);
            if (!ok)
                throw new ApplicationException(string.Format("Windows API call error {0}.", Marshal.GetLastWin32Error()));
        }
    }

    internal static class WindowsApi
    {
        public const int LOCALE_ITIME = 0x00000023;

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool SetLocaleInfo(uint locale, uint lcType, string lcData);
    }
}

请注意,SetLocalInfo文档说明在对系统参数进行国际更改后,有必要向所有顶级窗口广播WM_SETTINGCHANGE消息。执行此操作将需要使用另一个Windows API函数SendMessageTimeout。该部分在示例中省略。