C# 以编程方式更改系统日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/650849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change system date programmatically
提问by Yoann. B
How can I change the local system's date & time programmatically with C#?
如何使用 C# 以编程方式更改本地系统的日期和时间?
采纳答案by Andrew Hare
Here is where I found the answer.; I have reposted it here to improve clarity.
这是我找到答案的地方。; 我在这里重新发布它以提高清晰度。
Define this structure:
定义这个结构:
[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;
}
Add the following extern
method to your class:
将以下extern
方法添加到您的类中:
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetSystemTime(ref SYSTEMTIME st);
Then call the method with an instance of your struct like this:
然后使用结构的实例调用该方法,如下所示:
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.
回答by Avram
- PInvoke to call Win32 API SetSystemTime,(example)
- System.Management classes with WMI class Win32_OperatingSystem and call SetDateTime on that class.
- PInvoke 调用 Win32 API SetSystemTime,(示例)
- System.Management 类与 WMI 类 Win32_OperatingSystem 并在该类上调用 SetDateTime。
Both require that the caller has been granted SeSystemTimePrivilege and that this privilege is enabled.
两者都要求调用者已被授予 SeSystemTimePrivilege 并启用此权限。
回答by MarmouCorp
You can use a call to a DOS command but the invoke of the function in the windows dll is a better way to do it.
您可以使用对 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);
}
回答by Dаn
Since I mentioned it in a comment, here's a C++/CLI wrapper:
由于我在评论中提到了它,这里有一个 C++/CLI 包装器:
#include <windows.h>
namespace JDanielSmith
{
public ref class Utilities abstract sealed /* abstract sealed = static */
{
public:
CA_SUPPRESS_MESSAGE("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")
static void SetSystemTime(System::DateTime dateTime) {
LARGE_INTEGER largeInteger;
largeInteger.QuadPart = dateTime.ToFileTimeUtc(); // "If your compiler has built-in support for 64-bit integers, use the QuadPart member to store the 64-bit integer."
FILETIME fileTime; // "...copy the LowPart and HighPart members [of LARGE_INTEGER] into the FILETIME structure."
fileTime.dwHighDateTime = largeInteger.HighPart;
fileTime.dwLowDateTime = largeInteger.LowPart;
SYSTEMTIME systemTime;
if (FileTimeToSystemTime(&fileTime, &systemTime))
{
if (::SetSystemTime(&systemTime))
return;
}
HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
throw System::Runtime::InteropServices::Marshal::GetExceptionForHR(hr);
}
};
}
The C# client code is now very simple:
C# 客户端代码现在非常简单:
JDanielSmith.Utilities.SetSystemTime(DateTime.Now);
回答by Derek W
A lot of great viewpoints and approaches are already here, but here are some specifications that are currently left out and that I feel might trip up and confuse some people.
这里已经有很多很棒的观点和方法,但这里有一些规范目前被遗漏了,我觉得可能会绊倒并混淆一些人。
- On Windows Vista, 7, 8 OSthis will requirea UAC Prompt in order to obtain the necessary administrative rights to successfully execute the
SetSystemTime
function. The reason is that calling process needs the SE_SYSTEMTIME_NAMEprivilege. - The
SetSystemTime
function is expecting aSYSTEMTIME
struct in coordinated universal time (UTC). It will not work as desired otherwise.
- 在Windows Vista、7、8 操作系统上,这将需要UAC 提示以获得成功执行该
SetSystemTime
功能所需的管理权限。原因是调用进程需要SE_SYSTEMTIME_NAME权限。 - 该
SetSystemTime
函数需要一个SYSTEMTIME
协调世界时(UTC)的结构体。否则它将无法正常工作。
Depending on where/ how you are getting your DateTime
values, it might be best to play it safe and use ToUniversalTime()
before setting the corresponding values in the SYSTEMTIME
struct.
根据获取DateTime
值的位置/方式,最好ToUniversalTime()
在设置SYSTEMTIME
结构中的相应值之前安全使用并使用它。
Code example:
代码示例:
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);
回答by Hiren Raiyani
Use this function to change the time of system (tested in window 8)
使用此功能更改系统时间(在窗口 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();
}
}
Example:Call in load method of formsetDate("5-6-92"); setTime("2:4:5 AM");
示例:调用表单setDate("5-6-92"); 的load 方法;setTime("2:4:5 AM");
回答by Javad_Raouf
proc.Arguments = "/C Date:" + dateInYourSystemFormat;
proc.Arguments = "/C 日期:" + dateInYourSystemFormat;
This Is Work Function:
这是工作功能:
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();
}
}
回答by Yusuf GURDAG
Be Careful!. If you delete unused property from the structure, it sets the time wrong. I ve lost 1 day because of this. I think order of the structure is important.
当心!。如果您从结构中删除未使用的属性,则会将时间设置错误。因为这个,我失去了 1 天。我认为结构的顺序很重要。
This is correct structure:
这是正确的结构:
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;
};
If you run the SetSystemTime(), it works as expected. For test I set the time as below;
如果您运行 SetSystemTime(),它会按预期工作。为了测试,我将时间设置如下;
SystemTime st = new SystemTime();
st.Year = 2019;
st.Month = 10;
st.Day = 15;
st.Hour = 10;
st.Minute = 20;
st.Second = 30;
SetSystemTime(ref st);
The time set: 15.10.2019 10:20, its ok.
时间设定:15.10.2019 10:20,没关系。
But I delete DayOfWeek property which not used ;
但我删除了未使用的 DayOfWeek 属性;
public struct SystemTime
{
public ushort Year;
public ushort Month;
public ushort Day;
public ushort Hour;
public ushort Minute;
public ushort Second;
public ushort Millisecond;
};
SystemTime st = new SystemTime();
st.Year = 2019;
st.Month = 10;
st.Day = 15;
st.Hour = 10;
st.Minute = 20;
st.Second = 30;
SetSystemTime(ref st);
Run same code but the time set to: 10.10.2019 20:30
运行相同的代码,但时间设置为:10.10.2019 20:30
Please be careful order and all fields of SystemTime structure. Yusuf
请小心顺序和 SystemTime 结构的所有字段。优素福