C#设置系统本地时间代码实例
作者:韩明剑
时间:2021-07-06
浏览:1568
点赞:0

概述:

使用C#代码设置当前系统本地时间的实例

注意:

需以管理员身份运行才可设置成功

代码:

using System;
using System.Runtime.InteropServices;

namespace LocalTimeSync
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime dt = DateTime.Parse("2021-07-06 08:50:10.126");
            Console.WriteLine(SetTime(dt));
            Console.ReadKey();
        }
        [DllImport("Kernel32.dll")]
        public static extern bool SetLocalTime(ref SystemTime sysTime);
        public 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 wMiliseconds;
        }
        public static string SetTime(DateTime currentTime)
        {
            SystemTime sysTime = new SystemTime();
            sysTime.wYear = Convert.ToUInt16(currentTime.Year);
            sysTime.wMonth = Convert.ToUInt16(currentTime.Month);
            sysTime.wDay = Convert.ToUInt16(currentTime.Day);
            sysTime.wDayOfWeek = Convert.ToUInt16(currentTime.DayOfWeek);
            sysTime.wHour = Convert.ToUInt16(currentTime.Hour);
            sysTime.wMinute = Convert.ToUInt16(currentTime.Minute);
            sysTime.wSecond = Convert.ToUInt16(currentTime.Second);
            sysTime.wMiliseconds = Convert.ToUInt16(currentTime.Millisecond);

            string msg = "";
            if (SetLocalTime(ref sysTime))
            {
                msg = "修改成功";
            }
            else
            {
                msg = "修改失败";
            }
            return msg;
        }
    }
}

原创不易,转载请保留本站版权。