C#修改系统时间

使用C#更改Windows系统时间的方法。

第一种方法:调用系统API函数更改系统时间

[StructLayout(LayoutKind.Sequential)]
    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 class SetSystemDateTime
    {
       [DllImport("Kernel32.dll")]
       public static extern bool SetLocalTime(ref SystemTime sysTime);

       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 = SetSystemDateTime.SetLocalTime(ref sysTime);
           }
           catch (Exception e)
           {
               Console.WriteLine("SetSystemDateTime函数执行异常" + e.Message);
           }
           return flag;
       }
    }

第二种方法:就是利用Process类调用DOC命令更改系统时间

 

             //实例一个Process类,启动一个独立进程 
             Process p = new Process(); 
               //Process类有一个StartInfo属性 
             //设定程序名 
             p.StartInfo.FileName = "cmd.exe";
             //设定程式执行参数    “/C”表示执行完命令后马上退出
             p.StartInfo.Arguments = "/c date 2020-2-20";  
              //关闭Shell的使用   
            p.StartInfo.UseShellExecute = false;    
            //重定向标准输入      
            p.StartInfo.RedirectStandardInput = true;  
            p.StartInfo.RedirectStandardOutput = true; 
              //重定向错误输出   
           p.StartInfo.RedirectStandardError = true;   
              //设置不显示doc窗口  
            p.StartInfo.CreateNoWindow = true;           
            //启动 
            p.Start(); 

          //从输出流取得命令执行结果 
           return p.StandardOutput.ReadToEnd();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值