在项目中需要和服务器对时,时间不同,需要修改本机时间,在网上找到的代码都大同小异,共同点就是都改不了本机时间。
修改本机时间和系统有关系吗?谁能提供份可用的代码啊,我现在毫无头绪!
管理员身份运行程序,
设置的新时间要是UTC时间,不是北京时间
using System;
using System.Runtime.InteropServices;
namespace ConsoleApp2
{
public struct SystemTime
{
public ushort Year;
public ushort Month;
public ushort DayOfWeek;
public ushort Day;
public ushort Hour;
public ushort Minute;
public ushort Second;
public ushort Milliseconds;
}
internal class Program
{
[DllImport("Kernel32.dll")]
private static extern int SetSystemTime(in SystemTime systemTime);
private static void Main(string[] args)
{
//需要管理员身份运行程序!
//设置UTC时间,不是北京时间
SystemTime newTime = new SystemTime
{
Year = 2021,
Month = 8,
DayOfWeek = 2,
Day = 31,
Hour = 12,
Minute = 40,
Second = 0,
Milliseconds = 0
};
if (SetSystemTime(newTime) != 0)
{
Console.WriteLine("系统时间设置成功!");
}
else
{
Console.WriteLine("系统时间设置失败!");
Console.WriteLine("需要管理员身份运行程序!");
}
Console.ReadKey();
}
}
}
后台你想要改客户机的时间?那怕是要起飞哟
直接改是改不了了,但是可以想想其他办法,比如cmd
Process proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.Start();
proc.StandardInput.WriteLine("@date 2022-12-12");
proc.StandardInput.WriteLine("@time 12:59");
proc.StandardInput.AutoFlush = true;
proc.Close();
proc.Dispose();