Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

.net - How do I set the Windows system clock to the correct local time using C#?

How do I set the Windows system clock to the correct local time using C#?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will need to P/Invoke the SetLocalTime function from the Windows API. Declare it like this in C#:

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool SetLocalTime(ref SYSTEMTIME lpSystemTime);

[StructLayout(LayoutKind.Sequential)]
internal struct SYSTEMTIME
{
    public ushort wYear;
    public ushort wMonth;
    public ushort wDayOfWeek;    // ignored for the SetLocalTime function
    public ushort wDay;
    public ushort wHour;
    public ushort wMinute;
    public ushort wSecond;
    public ushort wMilliseconds;
}

To set the time, you simply initialize an instance of the SYSTEMTIME structure with the appropriate values, and call the function. Sample code:

SYSTEMTIME time = new SYSTEMTIME();
time.wDay = 1;
time.wMonth = 5;
time.wYear = 2011;
time.wHour = 12;
time.wMinute = 15;

if (!SetLocalTime(ref time))
{
    // The native function call failed, so throw an exception
    throw new Win32Exception(Marshal.GetLastWin32Error());
}

However, note that the calling process must have the appropriate privileges in order to call this function. In Windows Vista and later, this means you will have to request process elevation.


Alternatively, you could use the SetSystemTime function, which allows you to set the time in UTC (Coordinated Universal Time). The same SYSTEMTIME structure is used, and the two functions are called in an identical fashion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...