C#实现通过调用Win32 API修改计算机的日期时间

C#实现通过调用Win32 API修改计算机的日期时间

  • 背景
  • 代码实现
  • 注意点

背景

在分布式多系统协同工作共同构成一个庞大的信息化系统时,往往需要一台时间同步服务器,其他计算机的节点要定时跟此服务器进行时间同步,就需要程序修改计算机的日期时间,下面就把C#调用Win32 API的实现方式进行一下分享。

代码实现

LocalTime

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace Mesnac.Basic
{
    public class LocalTime
    {
        //设定,获取系统时间,SetSystemTime()默认设置的为UTC时间,比北京时间少了8个小时。  
        [DllImport("Kernel32.dll")]
        private static extern bool SetSystemTime(ref SystemTime time);
        [DllImport("Kernel32.dll")]
        private static extern bool SetLocalTime(ref SystemTime time);
        [DllImport("Kernel32.dll")]
        private static extern void GetSystemTime(ref SystemTime time);
        [DllImport("Kernel32.dll")]
        private static extern void GetLocalTime(ref SystemTime time);

        //struct for date/time apis 
        private struct SystemTime
        {
            public ushort wYear;
            public ushort wMonth;
            public ushort wDayOfWeek;
            public ushort wDay;
            public ushort wHour;
            public ushort wMinute;
            public ushort wSecond;
            public ushort wMilliseconds;
        }

        public void Set(DateTime dt)
        {
            SystemTime time = new SystemTime();
            time.wYear = (ushort)dt.Year;
            time.wMonth = (ushort)dt.Month;
            time.wDayOfWeek = (ushort)dt.DayOfWeek;
            time.wDay = (ushort)dt.Day;
            time.wHour = (ushort)dt.Hour;
            time.wMinute = (ushort)dt.Minute;
            time.wSecond = (ushort)dt.Second;
            time.wMilliseconds = (ushort)dt.Millisecond;
            SetLocalTime(ref time);
        }

        /// 
        /// 设置本地系统时间
        /// 
        /// 能够转换为时间格式的字符串变量
        /// 设置成功返回true,否则返回false
        public static bool SetLocalTimeByStr(string timestr)
        {
            bool flag = false;
            SystemTime sysTime = new SystemTime();
            DateTime dt = Convert.ToDateTime(timestr);
            sysTime.wYear = Convert.ToUInt16(dt.Year);
            sysTime.wMonth = Convert.ToUInt16(dt.Month);
            sysTime.wDay = Convert.ToUInt16(dt.Day);
            sysTime.wHour = Convert.ToUInt16(dt.Hour);
            sysTime.wMinute = Convert.ToUInt16(dt.Minute);
            sysTime.wSecond = Convert.ToUInt16(dt.Second);
            try
            {
                flag = SetLocalTime(ref sysTime);
            }
            catch (Exception e)
            {
                ICSharpCode.Core.LoggingService<LocalTime>.Error("SetSystemDateTime函数执行异常:" + e.Message);
            }
            return flag;
        }
    }
}

注意点

1、因为我在封装的时候依赖了ICSharpCode.Core,如果您没有ICSharpCode,请把上面代码中使用

ICSharpCode.Core.LoggingService<LocalTime>.Error

的地方修改为

Console.WriteLine

你可能感兴趣的:(工具类)