5

What is the best way to set the machine time in C#?

5
  • dup? stackoverflow.com/questions/204936/…
    – kenny
    Commented Aug 2, 2010 at 20:59
  • @kenny: I don't think so... that's talking about remote machines.
    – Jon Skeet
    Commented Aug 2, 2010 at 21:01
  • That comment isn't an exact duplicate, as that question is asking how to do this on a remote machine. Commented Aug 2, 2010 at 21:01
  • @kenny: This is not a duplicate question to the question you linked. The difference between the questions is that this question asks how to set the local machine time, and the question you linked is how to set the remote machine time. However, the answers are the same :) Commented Aug 2, 2010 at 21:03
  • OK, not a dup, but the answer is.
    – kenny
    Commented Aug 2, 2010 at 21:26

2 Answers 2

7

You'll probably need to use the Win32 API to do this, as I'm fairly sure there's nothing baked into the framework:

[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; 
 } 
 [DllImport("kernel32.dll", SetLastError=true)] 
public static extern bool SetSystemTime(ref SYSTEMTIME theDateTime );

There's a fuller example at PInvoke.net, the code's a bit dense, but a simple excerpt that's fairly plain to read and understand is this:

SYSTEMTIME st = new SYSTEMTIME();
GetSystemTime(ref st);
// Adds one hour to the time that was retrieved from GetSystemTime
st.wHour = (ushort)(st.wHour + 1 % 24);
var result = SetSystemTime(ref st);
if (result == false)
{
     // Something went wrong
}
else
{
    // The time will now be 1hr later than it was previously
}

The relevant specific Win32 API's are SetSystemTime, GetSystemTime and the SYSTEMTIME structure.

2
  • 2
    Just as a heads up, you'll need adminstrator permissions to set the system time. A standard user cannot change the time.
    – Joshua
    Commented Aug 2, 2010 at 21:04
  • You defined SetSystemTime to return a bool but check if the result == 0. Commented Aug 2, 2010 at 21:07
1

Microsoft.VisualBasic.DateAndTime.TimeOfDay = dateTime;

Add a reference of Microsoft.VisualBasic to you project Please let me know if any issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.