2009-03-16 46 views
37

Làm cách nào để thay đổi ngày của hệ thống cục bộ & theo thời gian bằng C#?Thay đổi ngày hệ thống lập trình

+7

hài hước như thế nào một số câu hỏi như thế này chỉ nhận được trả lời, trong khi những người khác được spam với ... lạ ... –

Trả lời

60

Here is where I found the answer.

Tôi đã đăng lại ở đây để cải thiện độ rõ nét.

Xác định cấu trúc này:

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

Thêm phương pháp extern sau để lớp học của bạn:

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

Sau đó gọi phương thức với một thể hiện của cấu trúc của bạn như thế này:

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. 
+4

viết một trình bao bọc C++/CLI tùy chỉnh và introcuding một assembly khác dễ hơn viết một cấu trúc 9 dòng? – Lucas

+4

Không gian tên Microsoft.VisualStudio.Shell.Interop chứa một cấu trúc của cấu trúc SYSTEMTIME; xem http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.shell.interop.systemtime.aspx –

+0

Chỉ cần không để Marc Gravell xem cấu trúc của bạn! ;-) – si618

7
  1. PInvoke gọi Win32 API SetSystemTime, (example)
  2. lớp System.Management với lớp WMI Win32_OperatingSystem và gọi SetDateTime trên lớp đó.

Cả hai yêu cầu người gọi đã được cấp SeSystemTimePrivilege và đặc quyền này được bật.

14

Bạn có thể sử dụng lệnh gọi đến lệnh DOS nhưng lệnh gọi hàm trong cửa sổ dll là một cách tốt hơn để làm điều đó.

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); 
} 
4

Kể từ khi tôi đề cập đến nó trong một chú thích, đây là một 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); 
     } 
    }; 
} 

C# mã khách hàng bây giờ rất đơn giản:

JDanielSmith.Utilities.SetSystemTime(DateTime.Now); 
+0

Tôi đã thử mã của bạn, nhưng nó dường như không hoạt động. https://gist.github.com/jtara1/07cfd5ebffab8296564f86000c50510e Anyways, tôi tìm thấy giải pháp cho những gì tôi muốn và thử nghiệm nó ra https://github.com/jtara1/MiscScripts/blob/00a5d330d784d7e423c0f8a83172ddfc31aad3fa/MiscScripts/UpdateOSTime.cs –

8

Rất nhiều quan điểm vĩ đại và phương pháp tiếp cận đã có ở đây, nhưng đây là một số thông số kỹ thuật hiện đang bị loại bỏ và tôi cảm thấy có thể đi lên và gây nhầm lẫn cho một số người.

  1. On Windows Vista, 7, 8 OS này sẽ đòi hỏi một Prompt UAC để có được các quyền quản trị cần thiết để thực hiện thành công các SetSystemTime chức năng. Lý do là quá trình gọi cần có đặc quyền SE_SYSTEMTIME_NAME.
  2. Chức năng SetSystemTime đang mong đợi cấu trúc SYSTEMTIME trong thời gian quốc tế được phối hợp (UTC). Nó sẽ không hoạt động như mong muốn khác.

Tùy thuộc vào nơi/làm thế nào bạn đang nhận được DateTime giá trị của bạn, nó có thể là tốt nhất để chơi nó an toàn và sử dụng ToUniversalTime() trước khi thiết lập các giá trị tương ứng trong SYSTEMTIME struct.

Mã dụ:

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); 
+0

I không thể trực tiếp thay đổi thời gian hệ thống bằng cách sử dụng –

+0

Tôi đã sử dụng mã này trên nhiều dự án thành công. Bạn có đang chạy tệp thực thi với tư cách là quản trị viên không? Nếu không mã này chắc chắn sẽ không hoạt động. –

+1

wow điều này giải quyết được vấn đề của tôi. Vấn đề là múi giờ cho thời gian địa phương của bạn là nhận được trong cách để có được thời gian chính xác để dòng "DateTime dateTime = tempDateTime.ToUniversalTime();" giải quyết tất cả. –

5

Sử dụng chức năng này để thay đổi thời gian của hệ thống (thử nghiệm trong cửa sổ 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(); 
     } 
    } 

Ví dụ: Gọi trong phương pháp tải trọng của hình thức setDate ("5-6-92"); setTime ("2: 4: 5 AM");

+0

Dưới đây là một thử nghiệm, sẵn sàng để biên dịch và chạy phiên bản mã của bạn https://github.com/jtara1/MiscScripts/blob/master/MiscScripts/UpdateOSTime.cs Tôi phải trải qua ít nhất 4 stackoverflows cho điều này vì tôi không quen thuộc với C# hoặc các libs này. –

-2

proc.Arguments = "/ C Date:" + dateInYourSystemFormat;

This Is Chức năng làm việc: "những gì đã bạn đã cố gắng"

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(); 
    } 
} 
+0

cùng một câu trả lời bạn đã đưa ra ... –

Các vấn đề liên quan