以编程方式更改系统日期

Yoa*_*. B 52 c# time datetime date system

如何使用C#以编程方式更改本地系统的日期和时间?

And*_*are 82

这是我找到答案的地方.

我在这里重新发布它以提高清晰度.

定义这个结构:

[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
    public short wYear;
    public short wMonth;
    public short wDayOfWeek;
    public short wDay;
    public short wHour;
    public short wMinute;
    public short wSecond;
    public short wMilliseconds;
}
Run Code Online (Sandbox Code Playgroud)

将以下extern方法添加到您的类:

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetSystemTime(ref SYSTEMTIME st);
Run Code Online (Sandbox Code Playgroud)

然后使用结构的实例调用该方法,如下所示:

SYSTEMTIME st = new SYSTEMTIME();
st.wYear = 2009; // must be short
st.wMonth = 1;
st.wDay = 1;
st.wHour = 0;
st.wMinute = 0;
st.wSecond = 0;

SetSystemTime(ref st); // invoke this method.
Run Code Online (Sandbox Code Playgroud)

  • Microsoft.VisualStudio.Shell.Interop命名空间包含SYSTEMTIME结构的定义; 请参阅http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.shell.interop.systemtime.aspx (6认同)
  • 编写自定义C++/CLI包装器并插入另一个程序集比编写~9行结构更容易? (4认同)
  • 可以说这种方法设置了UTC时间.因此,如果您按当地时间Datetime.Now,那么它将设置错误的时间.我遇到了这个,很长一段时间都无法理解什么是错的...... (4认同)
  • 值得一提的是,该程序需要管理员权限才能运行... (4认同)
  • 由于某种原因,我对答案的编辑被拒绝,但至少对于 Win 7,我发现我需要以管理员身份运行该程序才能正常工作。请参阅:http://stackoverflow.com/questions/2818179/how-to-force-my-net-app-to-run-as-administrator-on-windows-7 (3认同)

Mar*_*orp 15

您可以使用对DOS命令的调用,但是在Windows dll中调用该函数是一种更好的方法.

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 Millisecond;
};

[DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
public extern static void Win32GetSystemTime(ref SystemTime sysTime);

[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
public extern static bool Win32SetSystemTime(ref SystemTime sysTime);

private void button1_Click(object sender, EventArgs e)
{
    // Set system date and time
    SystemTime updatedTime = new SystemTime();
    updatedTime.Year = (ushort)2009;
    updatedTime.Month = (ushort)3;
    updatedTime.Day = (ushort)16;
    updatedTime.Hour = (ushort)10;
    updatedTime.Minute = (ushort)0;
    updatedTime.Second = (ushort)0;
    // Call the unmanaged function that sets the new date and time instantly
    Win32SetSystemTime(ref updatedTime);
}  
Run Code Online (Sandbox Code Playgroud)


Der*_*k W 12

很多很棒的观点和方法已经在这里,但是这里有一些目前被遗漏的规范,我觉得可能会绊倒并迷惑一些人.

  1. Windows Vista,7,8 OS上,这将需要 UAC提示,以获得成功执行该SetSystemTime功能所需的管理权限.原因是调用进程需要SE_SYSTEMTIME_NAME权限.
  2. SetSystemTime函数期望SYSTEMTIME协调世界时(UTC)中的结构.否则它将无法正常工作.

根据您获取DateTime值的位置/方式,最好ToUniversalTime()SYSTEMTIME结构中设置相应的值之前安全地使用它.

代码示例:

DateTime tempDateTime = GetDateTimeFromSomeService();
DateTime dateTime = tempDateTime.ToUniversalTime();

SYSTEMTIME st = new SYSTEMTIME();
// All of these must be short
st.wYear = (short)dateTime.Year;
st.wMonth = (short)dateTime.Month;
st.wDay = (short)dateTime.Day;
st.wHour = (short)dateTime.Hour;
st.wMinute = (short)dateTime.Minute;
st.wSecond = (short)dateTime.Second;

// invoke the SetSystemTime method now
SetSystemTime(ref st); 
Run Code Online (Sandbox Code Playgroud)

  • 我已在多个项目中成功使用此代码。您是否以管理员身份运行可执行文件?否则这段代码肯定无法工作。 (2认同)
  • 哇这个解决了我的问题。问题是本地时间的时区妨碍了获取正确时间,因此行“DateTime dateTime = tempDateTime.ToUniversalTime();” 解决了这一切。 (2认同)

Avr*_*ram 7

  1. PInvoke调用Win32 API SetSystemTime,(示例)
  2. 具有WMI类Win32_OperatingSystem的System.Management类,并在该类上调用SetDateTime.

两者都要求调用者已被授予SeSystemTimePrivilege并且已启用此权限.


Hir*_*ani 6

使用此功能更改系统时间(在窗口8中测试)

 void setDate(string dateInYourSystemFormat)
    {
        var proc = new System.Diagnostics.ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = @"C:\Windows\System32";
        proc.CreateNoWindow = true;
        proc.FileName = @"C:\Windows\System32\cmd.exe";
        proc.Verb = "runas";
        proc.Arguments = "/C date " + dateInYourSystemFormat;
        try
        {
            System.Diagnostics.Process.Start(proc);
        }
        catch
        {
            MessageBox.Show("Error to change time of your system");
            Application.ExitThread();
        }
    }
void setTime(string timeInYourSystemFormat)
    {
        var proc = new System.Diagnostics.ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = @"C:\Windows\System32";
        proc.CreateNoWindow = true;
        proc.FileName = @"C:\Windows\System32\cmd.exe";
        proc.Verb = "runas";
        proc.Arguments = "/C time " + timeInYourSystemFormat;
        try
        {
            System.Diagnostics.Process.Start(proc);
        }
        catch
        {
            MessageBox.Show("Error to change time of your system");
            Application.ExitThread();
        }
    }
Run Code Online (Sandbox Code Playgroud)

示例: 调用表单 setDate的加载方法("5-6-92"); setTime("2:4:5 AM");


Wil*_*ood 5

为其他正在寻找复制/粘贴课程的人提供的复制/粘贴课程

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

public static class SystemDateTime
{
    [DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
    private static extern bool Win32SetSystemTime(ref SystemTime sysTime);

    [StructLayout(LayoutKind.Sequential)]
    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 Millisecond;
    };

    public static void SetSystemDateTime(int year, int month, int day, int hour,
        int minute, int second, int millisecond)
    {
        SystemTime updatedTime = new SystemTime
        {
            Year = (ushort) year,
            Month = (ushort) month,
            Day = (ushort) day,
            Hour = (ushort) hour,
            Minute = (ushort) minute,
            Second = (ushort) second,
            Millisecond = (ushort) millisecond
        };

        // If this returns false, then the problem is most likely that you don't have the 
        // admin privileges required to set the system clock
        if (!Win32SetSystemTime(ref updatedTime))
        {
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }
    }

    public static void SetSystemDateTime(DateTime dateTime)
    {
        SetSystemDateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute,
            dateTime.Second, dateTime.Millisecond);
    }
}
Run Code Online (Sandbox Code Playgroud)